Let’s say I have a string which contains this:
HelloxxxHelloxxxHello
I compile a pattern to look for ‘Hello’
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher("HelloxxxHelloxxxHello");
It should find three matches. How can I get a count of how many matches there were?
I’ve tried various loops and using the matcher.groupCount() but it didn’t work.
matcher.find()does not find all matches, only the next match.Solution for Java 9+
Solution for Java 8 and older
You’ll have to do the following. (Starting from Java 9, there is a nicer solution)
Btw,
matcher.groupCount()is something completely different.Complete example:
Handling overlapping matches
When counting matches of
aainaaaathe above snippet will give you 2.To get 3 matches, i.e. this behavior:
You have to search for a match at index
<start of last match> + 1as follows: