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.
1 |
boolean find() |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.javacodeexamples.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegExCountMatcheExample { public static void main(String[] args) { String sourceString = "I got 90 out of 100 marks in test"; //pattern to extract number from text String strPattern = "(\\d+)"; Pattern p = Pattern.compile(strPattern); Matcher m = p.matcher(sourceString); int count = 0; while( m.find() ) { //increment count of matches count++; } System.out.println("Match count is: " + count); } } |
Output
1 |
Match count is: 2 |
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.
1 |
long count = m.results().count(); |
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.