1

在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+)\\): (.*?);$"
);

模式末尾的(.*?)是因为它需要贪婪,但;在输入行的最末尾返回。

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

但是我的“休息”组在哪里?为什么整条线都是一个组?我检查了多个在线正则表达式测试站点,它应该可以工作:例如http://www.regexplanet.com/advanced/java/index.html看到 3 个捕获组。也许这与我目前正在使用 jdk 1.6 的事实有关?

4

1 回答 1

3

问题在于,groupCount迭代是 Java 中为数不多的实际需要达到count获取所有组的值的情况之一。

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

只需像这样增加您的计数器(注意<=而不是 just <):

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

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

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

总而言之,Pattern括号中标记的显式组从 index 开始1

请参阅此处的文档。

于 2015-10-07T10:04:26.150 回答