Tuesday, December 23, 2014

Counting Group of Words and Searching a Word in java



Counting Group of Words
 
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);
   }
}

Searching a Word

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main 
{
   public static void main(String args[]) 
  {
      Pattern p = Pattern.compile("j(ava)");
      String candidateString = "This is a java program. 
      This is another java program.";
      Matcher matcher = p.matcher(candidateString);
      int nextIndex = matcher.start(1);
      System.out.println(candidateString);
      System.out.println("The index for java is:" + nextIndex);
   }
}

No comments:

Post a Comment