Tutorials Point


  Java Basics Examples
  Java Tutorial
  Java Useful Resources
  Selected Reading

© 2011 TutorialsPoint.COM


  Home     References     Discussion Forums     About TP  

Java Examples - Counting Group of Words


previous next AddThis Social Bookmark Button


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


previous next Printer Friendly



  

Advertisement

Online Image Processing

Indian Baby Names