3

I'm converting code from Javascript to Java and I found a regular expression that in Java doesn't work as expected (using the standard class Pattern).

It works fine in perl, js and also in Cocoa with NSRegularExpression

The reg exp is ([a-z]*) ([0-9]*) and the java code is shown below

It must match two groups separated by a space, the first group contains only letters, the second group only numbers

public static void main(String[] args) {
Matcher matcher = Pattern.compile("([a-z]*) ([0-9]*)").matcher("hello 101");
while (matcher.find()) {
    for (int i = 0; i < matcher.groupCount(); i++) {
        System.out.println(i + ": " + matcher.group(i));
    }
}

}

The numeric group is never returned. What is wrong?

4

1 回答 1

4

for过早结束循环:

for (int i = 0; i <= matcher.groupCount(); i++) {
//                ^^   
    System.out.println(i + ": " + matcher.group(i));
}

有两个捕获组,.groupCount()是 2:

  • .group(0)是整场比赛
  • .group(1)包含与第一个捕获组匹配的文本
  • .group(2)包含与第二个捕获组匹配的文本

如果您停i在 1 点,您将永远无法进入第二组。

于 2013-09-16T06:42:21.037 回答