3

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?

1

3 Answers 3

8

The method groupCount returns the number of groups in the Pattern.

Groups in a Pattern are parenthesis-delimited.

Your Pattern contains no groups.

If you are looking for the number of matches, use a while loop over the Matcher's find() method (which returns boolean).

For instance:

int myMatches = 0;
while (matcher.find()) {
    myMatches++;
}

Edit

Java 7+'s named groups are also parenthesis-delimited, although they follow a slightly more complex syntax than unnamed groups.

See here for details.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

You need to use paranthesis () in your regex for grouping. Refer this article for detailed explaination.

In your case Pattern pattern = Pattern.compile("@"); will just create default group with entire pattern. Hence you get the output as 0.

Try this instead:

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

I've trying to count how many matching patterns are there in a string

I think you want to determine the number of patterns found in the string. Unfortunately, grouping is not used for counting the number of matches.

You need to do something like this:

    int totalMatches = 0;
    while(matcher.find()) {
        // Number of pattern matches found in the String
        totalMatches++;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.