/** * @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:wl.wwautturi.com
output:
the number of matches:2
/** * @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