小编典典
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。
aaaa
aa
aa
要获得3个匹配项,即此行为:
aaaa
aa
aa
aa
你必须在索引处搜索匹配项, + 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
2020-03-15