Java正则expression式匹配计数

比方说,我有一个文件,该文件包含这个:

HelloxxxHelloxxxHello 

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

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

然后,我使用inputstream来读取文件并将其转换为一个string,以便它可以正则expression式。

一旦匹配器在文件中find匹配项,就表示这一点,但它并不告诉我它find了多less匹配项; 只是它在String中find了一个匹配项。

所以,由于string比较短,我使用的缓冲区是200字节,所以应该find三个匹配的string。 然而,它只是说匹配,并没有提供我有多less匹配的计数。

计算string中发生匹配次数的最简单方法是什么? 我已经尝试了各种循环,并使用matcher.groupCount(),但我无法快速。

matcher.find()没有find所有匹配,只有下一个匹配。

你必须做到以下几点:

 int count = 0; while (matcher.find()) count++; 

顺便说一句, matcher.groupCount()是完全不同的东西。


完整的例子

 import java.util.regex.*; class Test { public static void main(String[] args) { String hello = "HelloxxxHelloxxxHello"; Pattern pattern = Pattern.compile("Hello"); Matcher matcher = pattern.matcher(hello); int count = 0; while (matcher.find()) count++; System.out.println(count); // prints 3 } } 

这应该适用于不相交的匹配:

 public static void main(String[] args) { String input = "aaaaaaaa"; String regex = "aa"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); int from = 0; int count = 0; while(matcher.find(from)) { count++; from = matcher.start() + 1; } System.out.println(count); }