如何计算正则表达式的匹配次数? [英] How can I count the number of matches for a regex?
问题描述
假设我有一个包含以下内容的字符串:
Let's say I have a string which contains this:
HelloxxxHelloxxxHello
我编译了一个模式来寻找你好"
I compile a pattern to look for 'Hello'
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher("HelloxxxHelloxxxHello");
它应该找到三个匹配项.如何计算匹配的次数?
It should find three matches. How can I get a count of how many matches there were?
我尝试了各种循环并使用了 matcher.groupCount()
但它没有用.
I've tried various loops and using the matcher.groupCount()
but it didn't work.
推荐答案
matcher.find()
没有找到所有匹配,只找到next 匹配.
matcher.find()
does not find all matches, only the next match.
long matches = matcher.results().count();
Java 8 及更早版本的解决方案
您必须执行以下操作.(从 Java 9 开始,有一个更好的解决方案)
int count = 0;
while (matcher.find())
count++;
顺便说一句,matcher.groupCount()
是完全不同的东西.
Btw, matcher.groupCount()
is something completely different.
完整示例:
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
}
}
处理重叠匹配
当计算 aaaa
中 aa
的匹配项时,上面的代码片段会给你 2.
Handling overlapping matches
When counting matches of aa
in aaaa
the above snippet will give you 2.
aaaa
aa
aa
要获得 3 个匹配项,即这种行为:
To get 3 matches, i.e. this behavior:
aaaa
aa
aa
aa
您必须在索引
如下:
You have to search for a match at index <start of last match> + 1
as follows:
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
这篇关于如何计算正则表达式的匹配次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!