在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 的事实有关?