【发布时间】:2023-03-21 01:52:02
【问题描述】:
我正在尝试验证一个字符串,它必须具有正确顺序的特定模式,并进一步将它们分成组。
我的预期格式是 \60####### 或 \60000000 其中
- 它只能以一个“\”开头
- 后跟一位或多位数字(60 为示例,可以是任意数字)
- 后跟零个或多个“#”
- 没有别的东西
可能的匹配是这样的
- \60000000000
- \60###
- \60############
- \58342##
所以我在下面编译了正则表达式来尝试验证,并进一步将其分成组(期望 2 组(不带 #)或 3 组(带 #)):
Pattern numPattern = Pattern.compile("(\\\\{1})|([0-9]+)|(#*)");
我正在尝试检测 1 x \,1 个或多个 0 到 9,任意数量的 #。
和单元测试:
private static void digest(String formatTxt) {
System.out.println("Doing: " + formatTxt);
Pattern numPattern = Pattern.compile("(\\\\{1})|([0-9]+)|(#*)");
if (numPattern.matcher(formatTxt).find()) {
System.out.println("Pattern matched!");
}
int i = 0;
Matcher matcher = numPattern.matcher(formatTxt);
while (matcher.find()) {
i++;
String data = matcher.group();
System.out.println(i + ". " + data);
}
System.out.println("");
}
public static void main(String[] args) {
digest("\\60000000000");
digest("\\6000000000000");
digest("\\60#########");
digest("\\60############");
digest("\\60############6");
digest("\\60########A####");
digest("\\lala60000000000");
digest("\\60#####6######");
digest("\\60#####6##A####");
}
结果:
// Doing: \60000000000
// Pattern matched!
// 1. \
// 2. 60000000000
// 3.
// Comment: OK but not sure why is there third element
//
// Doing: \6000000000000
// Pattern matched!
// 1. \
// 2. 6000000000000
// 3.
// Comment: OK but not sure why is there third element
//
// Doing: \60#########
// Pattern matched!
// 1. \
// 2. 60
// 3. #########
// 4.
// Comment: OK but not sure why is there forth element
//
// Doing: \60############
// Pattern matched!
// 1. \
// 2. 60
// 3. ############
// 4.
// Comment: OK but not sure why is there forth element
//
// Doing: \60############6
// Pattern matched!
// 1. \
// 2. 60
// 3. ############
// 4. 6
// 5.
// Comment: Not OK because I do not want anything behind #
//
// Doing: \60########A####
// Pattern matched!
// 1. \
// 2. 60
// 3. ########
// 4.
// 5. ####
// 6.
// Comment: Not OK because I do not want anything behind first group of #
//
// Doing: \lala60000000000
// Pattern matched!
// 1. \
// 2.
// 3.
// 4.
// 5.
// 6. 60000000000
// 7.
// Comment: Not OK because \\ must be followed by digits
//
// Doing: \60#####6######
// Pattern matched!
// 1. \
// 2. 60
// 3. #####
// 4. 6
// 5. ######
// 6.
// Comment: Not OK because I do not want anything behind first group of #
//
// Doing: \60#####6##A####
// Pattern matched!
// 1. \
// 2. 60
// 3. #####
// 4. 6
// 5. ##
// 6.
// 7. ####
// 8.
// Comment: Not OK because I do not want anything behind first group of #
如果有人可以指导我,我需要在正则表达式中进行哪些更改,以便实现上述要求?
【问题讨论】: