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