问题描述
我试图计算字符串中有多少匹配模式。我是使用java.util.regex的新手,我计划使用matcher.groupCount()来获取匹配组的数量。因为根据文档,它返回捕获组的数量。
I've trying to count how many matching patterns are there in a string. I'm new to using java.util.regex and I was planning on using matcher.groupCount() to get the number of matching groups. Since according to the documentation it returns the number of capturing groups.
组零表示按惯例的整个模式。此计数中不包括
。
Group zero denotes the entire pattern by convention. It is not included in this count.
任何小于或等于此方法返回的
的非负整数都保证是
匹配器的有效组索引。
Any non-negative integer smaller than or equal to the value returned by this method is guaranteed to be a valid group index for this matcher.
以下是我的问题的简化示例:
Here's a simplified example of my problem:
Pattern pattern = Pattern.compile("@");
Matcher matcher = pattern.matcher("@#@#@#@#@");
System.out.println(matcher.groupCount());
它的输出为0.我误解了哪一部分?如何计算匹配模式的数量?
Its output is 0. Which part did I misunderstand? How do I count the number of matching patterns?
推荐答案
方法 groupCount
返回模式
中的组数。
模式
中的组是括号分隔的。
Groups in a Pattern
are parenthesis-delimited.
您的模式
不包含任何组。
如果您要查找匹配数,请使用,而
循环 Matcher
的 find()
方法(返回 boolean
)。
If you are looking for the number of matches, use a while
loop over the Matcher
's find()
method (which returns boolean
).
例如:
int myMatches = 0;
while (matcher.find()) {
myMatches++;
}
这篇关于java.util.regex.Matcher中的groupCount()始终返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!