java.util.regex.Matcher中的groupCount()始终返回0 [英] groupCount() in java.util.regex.Matcher always returns 0

查看:405
本文介绍了java.util.regex.Matcher中的groupCount()始终返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算字符串中有多少匹配模式。我是使用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.


返回此匹配器模式中捕获组的数量。

Returns the number of capturing groups in this matcher's pattern.

组零表示按惯例的整个模式。此计数中不包括

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆