groupCount() in java.util.regex.Matcher always returns 0

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());

Its output is 0. Which part did I misunderstand? How do I count the number of matching patterns?

Jon Skeet
people
quotationmark

You haven't specified any capturing groups. If you change your pattern like this:

Pattern pattern = Pattern.compile("(@)");

then you'll have a capturing group - but it will still only return 1, as each match only has a single group. find() will return true 5 times though.

people

See more on this question at Stackoverflow