1
我写这个正则表达式:捕获组
String REGEX = "^\\s+something\\s+(not\\s+)?else\\s+((\\d+|\\d+-\\d+),\\s+)*(\\d+|\\d+-\\d+)$";
这里是我的主要方法:
public static void main(String... args) {
Matcher matcher = PATTERN.matcher(" something else 1, 3, 4, 5-7");
if (matcher.matches()) {
for (int index = 0; index <= matcher.groupCount(); index++) {
System.out.println(index + ": " + matcher.group(index));
}
}
}
,这里是我的输出:
0: match cos 1, 3, 4, 5-7
1: null
2: 4,
3: 4
4: 5-7
好像1
和3
没有被捕获。 (输出4
和5-7
都没问题。)如何修复我的正则表达式,以便我可以捕获它们(并在最后不用逗号捕获它们)?
谢谢,我会这样做。 – 2012-07-19 01:07:34
为了记录,'((\\ d + | \\ d + - \\ d +),\\ s +)*'部分与第一个重复中的“1”,第二个中的“”3“'匹配重复,然后在第三个也是最后一个重复中输入“4”。 – MRAB 2012-07-19 01:09:12