java正则表达式匹配计数

java正则表达式匹配计数

假设我有一个文件,该文件包含:

HelloxxxHelloxxxHello

我编译一个模式来寻找'你好'

Pattern pattern = Pattern.compile("Hello");

然后我使用输入流来读取文件并将其转换为String,以便可以对其进行重新编码。

一旦匹配器在文件中找到匹配项,它就表明了这一点,但它没有告诉我它找到了多少匹配项; 只是它在String中找到了一个匹配项。

因此,由于字符串相对较短,并且我使用的缓冲区是200字节,因此它应该找到三个匹配项。但是,它只是简单地说匹配,并没有向我提供有多少匹配的计数。

计算String中发生的匹配数的最简单方法是什么。我已经尝试了各种for循环并使用matcher.groupCount(),但我无处可去。


偶然的你
浏览 1712回答 3
3回答

眼眸繁星

matcher.find()没有找到所有的比赛,只有下一场比赛。你必须做以下事情:int&nbsp;count&nbsp;=&nbsp;0;while&nbsp;(matcher.find()) &nbsp;&nbsp;&nbsp;&nbsp;count++;顺便说一句,matcher.groupCount()是完全不同的东西。完整的例子:import&nbsp;java.util.regex.*;class&nbsp;Test&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;static&nbsp;void&nbsp;main(String[]&nbsp;args)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;hello&nbsp;=&nbsp;"HelloxxxHelloxxxHello"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Pattern&nbsp;pattern&nbsp;=&nbsp;Pattern.compile("Hello"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Matcher&nbsp;matcher&nbsp;=&nbsp;pattern.matcher(hello); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;count&nbsp;=&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while&nbsp;(matcher.find()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;count++; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(count);&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;prints&nbsp;3 &nbsp;&nbsp;&nbsp;&nbsp;}}处理重叠匹配当计算上述片段aa中aaaa的匹配时,您将获得2。aaaa aa &nbsp;&nbsp;aa要获得3个匹配,即此行为:aaaa aa &nbsp;aa &nbsp;&nbsp;aa您必须在索引中搜索匹配,<start of last match> + 1如下所示:String&nbsp;hello&nbsp;=&nbsp;"aaaa";Pattern&nbsp;pattern&nbsp;=&nbsp;Pattern.compile("aa");Matcher&nbsp;matcher&nbsp;=&nbsp;pattern.matcher(hello);int&nbsp;count&nbsp;=&nbsp;0;int&nbsp;i&nbsp;=&nbsp;0;while&nbsp;(matcher.find(i))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;count++; &nbsp;&nbsp;&nbsp;&nbsp;i&nbsp;=&nbsp;matcher.start()&nbsp;+&nbsp;1;}System.out.println(count);&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;prints&nbsp;3

幕布斯7119047

这适用于可能重叠的匹配:public&nbsp;static&nbsp;void&nbsp;main(String[]&nbsp;args)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;input&nbsp;=&nbsp;"aaaaaaaa"; &nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;regex&nbsp;=&nbsp;"aa"; &nbsp;&nbsp;&nbsp;&nbsp;Pattern&nbsp;pattern&nbsp;=&nbsp;Pattern.compile(regex); &nbsp;&nbsp;&nbsp;&nbsp;Matcher&nbsp;matcher&nbsp;=&nbsp;pattern.matcher(input); &nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;from&nbsp;=&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;count&nbsp;=&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;while(matcher.find(from))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;count++; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;from&nbsp;=&nbsp;matcher.start()&nbsp;+&nbsp;1; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;System.out.println(count);}
打开App,查看更多内容
随时随地看视频慕课网APP