Java Examples - Counting Group of Words

Advertisements


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


Advertisements
Advertisements