Match All Occurrences of a Regex in Java



public class RegexOccur {
   public static void main(String args[]) {
      String str = "java is fun so learn java";
      String findStr = "java";
      int lastIndex = 0;
      int count = 0;
      while(lastIndex != -1) {
         lastIndex = str.indexOf(findStr,lastIndex);
         if(lastIndex != -1) {
            count ++;
            lastIndex += findStr.length();
         }
      }
      System.out.println(count);
   }
}

Output

2
Updated on: 2020-06-23T14:46:06+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements