Skip to content

Java RegEx – Count Matches

Java RegEx – Count Matches example shows how to count matches in a string for a given regular expression pattern in Java using the find method of the Matcher class.

How to count the number of matches in a string using RegEx in Java?

The regular expressions in Java are used to do many text processing and one such use case is to just count the matches in the string for a given regular expression pattern instead of finding the matches.

There are a couple of ways in which we can count the matches in Java regex as given below.

1 Using the find method of the Matcher class

The find method of the Matcher class can be used to count matches.

The find method tries to find the next match of a substring in the given string. It returns true if it finds the match, false otherwise. Since we are not interested in extracting the actual match, we will just update the counter variable till we find the match.

Here is the example code using the find method to count the matches in the string.


As you can see from the output, since the string has two numbers, we got the count of 2 in the output.

Important Note:

The next invocation of the find method starts searching for the pattern at the start of the first character that is not matched by the current match. If you want to count the overlapping matches as well, you can use the find method that accepts an index parameter.

2 Using count method (Java 9 and above)

If you are using Java version 9 or above, you can use the count method of the results stream as given below.

The results method of the Matcher class returns the stream of the matched subsequences. The count operation on that stream using the count method returns the number of elements in the stream. For this example, that is the count of matches.

You can learn more about regex using regular expression in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.