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);
}
}
Example 2: number of matches regex java
long matches = matcher.results().count();
int count = 0;
while (matcher.find())
{
count++;
}