How to count a group of words in a string using Java



Problem Description

How to count a group of words in a string?

Solution

Following example demonstrates how to count a group of words in a string with the help of matcher.groupCount() method of regex.Matcher class.

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

public class MatcherGroupCountExample {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("J(ava)");
      String candidateString = "This is Java. This is a Java example.";
      Matcher matcher = p.matcher(candidateString);
      int numberOfGroups = matcher.groupCount();
      System.out.println("numberOfGroups =" + numberOfGroups);
   }
}

Result

The above code sample will produce the following result.

numberOfGroups = 3

The following is an example to to count a group of words in a string.

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

public class Main {
   public static void main(String[] args) {
      String s1 = "SairamkrishnaxxxxxMammahe";
      Pattern pattern = Pattern.compile("Sairamkrishna");
      Matcher  matcher = pattern.matcher(s1);
      int count = 0;
      
      while (matcher.find())count++;
      System.out.println(count);
   } 
}

The above code sample will produce the following result.

1
java_regular_exp.htm
Advertisements