matcher.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 }}Handling overlapping matches
当计算上述片段aa中aaaa的时,将为你提供2。
aaaaaa aa
要获得3个匹配项,即此行为:
aaaaaa aa aa
你必须在索引处搜索匹配项,
<start of last match> + 1如下所示:
String hello = "aaaa";Pattern pattern = Pattern.compile("aa");Matcher matcher = pattern.matcher(hello);int count = 0;int i = 0;while (matcher.find(i)) { count++; i = matcher.start() + 1;}System.out.println(count); // prints 3


