java.util.regex.Matcher中的groupCount()始终返回0
我试图计算字符串中有多少匹配模式。 我是使用java.util.regex的新手,我计划使用matcher.groupCount()来获取匹配组的数量。 因为根据文档,它返回捕获组的数量。
返回此匹配器模式中捕获组的数量。
组0表示按惯例的整个模式。 它不包含在此计数中。
小于或等于此方法返回的值的任何非负整数都保证是此匹配器的有效组索引。
这是我的问题的简化示例:
Pattern pattern = Pattern.compile("@"); Matcher matcher = pattern.matcher("@#@#@#@#@"); System.out.println(matcher.groupCount());
它的输出为0.我误解了哪一部分? 如何计算匹配模式的数量?
方法groupCount
返回Pattern
的组数。
Pattern
中的组是括号分隔的。
您的Pattern
包含任何组。
如果要查找匹配数,请在Matcher
的find()
方法(返回boolean
)上使用while
循环。
例如:
int myMatches = 0; while (matcher.find()) { myMatches++; }
您尚未指定任何捕获组。 如果你改变你的模式:
Pattern pattern = Pattern.compile("(@)");
那么你将拥有一个捕获组 – 但它仍将只返回1,因为每个匹配只有一个组。 find()
将返回true
5次。
您需要在正则表达式中使用paranthesis ()
进行分组。 请参阅本文以获取详细说明。
在你的情况下Pattern pattern = Pattern.compile("@");
将只创建整个模式的默认组。 因此,您将输出为0。
试试这个:
Pattern pattern = Pattern.compile("(@)");
我试图计算字符串中有多少匹配模式
我想你想确定字符串中找到的模式数量。 不幸的是,分组不用于计算匹配数。
你需要做这样的事情:
int totalMatches = 0; while(matcher.find()) { // Number of pattern matches found in the String totalMatches++; }