如何计算正则表达式的匹配项数?
假设我有一个字符串,其中包含以下内容:
HelloxxxHelloxxxHello
我编译一个模式来寻找“你好”
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher("HelloxxxHelloxxxHello");
它应该找到三个匹配项。如何计算有多少场比赛?
我尝试了各种循环并使用,但它不起作用。matcher.groupCount()
假设我有一个字符串,其中包含以下内容:
HelloxxxHelloxxxHello
我编译一个模式来寻找“你好”
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher("HelloxxxHelloxxxHello");
它应该找到三个匹配项。如何计算有多少场比赛?
我尝试了各种循环并使用,但它不起作用。matcher.groupCount()
matcher.find()找不到所有匹配项,只能找到下一个匹配项。
long matches = matcher.results().count();
您必须执行以下操作。(从Java 9开始,有一个更好的解决方案)
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
}
}
当计算上述代码段中的匹配项时,将为您提供2。aaaaaa
aaaa
aa
aa
要获得 3 个匹配项,即此行为:
aaaa
aa
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
这应该适用于可能重叠的匹配项:
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);
}