count the number of regex matches java code example

Example 1: regex count for matching in java

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

Example 2: number of matches regex java

// Java 9+
long matches = matcher.results().count();

// Java 8-
int count = 0;
while (matcher.find())
{
	count++;
}

Tags:

Java Example