正则表达式只在循环中使用find方法匹配一次

时间:2017-07-06 14:30:31

标签: java regex

我试图在Java中使用正则表达式来提取{}之间的所有结果,并一次一个地循环它们。

这是我使用的代码:

Pattern p = Pattern.compile("(\\{.*})");
Matcher m = p.matcher(validatePage);
while (m.find()) {
    JSONObject jsonObj = new JSONObject(m.group(1));
    System.out.println(jsonObj);
}

这是我正在搜索的文字

<tr><td class='warning'></td><td>test-testing-tester@2016-07-08.txt</td>
<td>TEST</td><td class='warningMessage'>[WARNING]</td><td 
class='warningMessage'>File with the revision 2016-07-08 validated 
successfully and is ready to be published. Warnings were detected. Please 
see report.</td></tr>
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, version is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, release is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.rxt","severity":"WARNING","lineNumber":43,"column":3,"offset":701,"length":118,"message":"extension, correction is missing"}
{"resourceUri":"test-testing-tester@2016-07-08.txt","severity":"WARNING","lineNumber":50,"column":3,"offset":825,"length":135,"message":"extension, version is missing"}

然而,m find()只循环一次,打印出第一个结果然后结束,我无法弄清楚原因。当我通过正则表达式匹配器运行它时,它会发现所有结果都很好。我是否缺少一些我需要做的事情来匹配每个结果并循环通过它?

1 个答案:

答案 0 :(得分:1)

您可以使用(\\{.*?})使您的正则表达式非贪婪

删除不需要的群组

Pattern p = Pattern.compile("\\{.*?}");
Matcher m = p.matcher(validatePage);
while (m.find()) {
    JSONObject jsonObj = new JSONObject(m.group());
    System.out.println(jsonObj);
}