count the number of matches for a regex in java

count the number of matches for a regex in java

For Java 8-

/**
 * @author lautturi.com 
 * Java example: find the number of matches using java regex
 */

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lautturi {
	
	public static void main(String[] args)   {

		String string = " hello java js learning java on lauttur1! ";
		String regexString = "java";
		Pattern pattern = Pattern.compile(regexString);
		
		Matcher matcher = pattern.matcher(string);
		int count = 0;
		while (matcher.find()) {
			count++;
		}
		System.out.println("the number of matches:"+count);

	}
}
Source:w‮l.ww‬autturi.com

output:

the number of matches:2

For Java 9+

/**
 * @author lautturi.com 
 * Java example: get the number of matches using java regex
 */

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lautturi {
	
	public static void main(String[] args)   {

		String string = " hello java js learning java on lauttur1! ";
		String regexString = "java";
		Pattern pattern = Pattern.compile(regexString);
		
		Matcher matcher = pattern.matcher(string);
		long count = matcher.results().count();
		System.out.println("the number of matches:"+count);

	}
}

output:

the number of matches:2
Created Time:2017-10-05 13:26:42  Author:lautturi