第二个捕获组不捕获

Second capturing group not capturing

在 java 中,我一直在尝试使用正则表达式解析日志文件。在日志文件的一行下方。

I 20151007 090137 - com.example.Main - Main.doStuff (293): ##identifier (id:21): {};

我需要行尾的 json 字符串和 id。这意味着我需要两个捕获组。所以我开始编码。

Pattern p = Pattern.compile(
  "^I [0-9]{8} [0-9]{6} - com\.example\.Main - Main\.doStuff \(\d+\): ##identifier \(id:(\d+)\): (.*?);$"
);

pattern最后的(.*?)是因为需要贪心,但是把输入行最后的;还给

Matcher m = p.matcher(readAboveLogfileLineToString());
System.err.println(m.matches() + ", " + m.groupCount());
for (int i = 0; i < m.groupCount(); i++) {
    System.out.println(m.group(i));
}

然而,上面的代码输出

true, 2
I 20151007 090137 - com.example.Main - Main.doStuff (293): ##identifier (id:21): {};
21

但是我的 "rest" 组在哪里?为什么整行是一个组?我检查了多个在线正则表达式测试站点,它应该可以工作:http://www.regexplanet.com/advanced/java/index.html 例如看到 3 个捕获组。可能是因为我目前使用的是 jdk 1.6?

问题是 groupCount 迭代是 Java 中您实际上需要达到 count 值才能获得所有组的少数情况之一。

在这种情况下,您需要迭代到组 2,因为组 0 实际上代表了整个匹配。

只需增加你的计数器(注意 <= 而不是 <):

for (int i = 0; i <= m.groupCount(); i++) {

最后打印的文本应该是:{}

当然,您也可以跳过 0 组,直接从 1 开始计数。

总而言之,Pattern 中带括号的显式组从索引 1.

开始

参见文档 here