Tuesday, December 23, 2014

Searching Duplicate Words and Finding Word Occurrence in java



Searching Duplicate Words

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main 
{
   public static void main(String args[]) throws Exception 
  {
      String duplicatePattern = "\\b(\\w+) \\1\\b";
      Pattern p = Pattern.compile(duplicatePattern);
      int matches = 0;
      String phrase = " this is a test ";
      Matcher m = p.matcher(phrase);
      String val = null;
      while (m.find()) {
         val = ":" + m.group() + ":";
         matches++;
      }
      if(val>0)
         System.out.println("The string 
         has matched with the pattern.");
      else
      System.out.println("The string 
      has not matched with the pattern.");
   }
}

Finding Word Occurrence

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main 
{
   public static void main(String args[]) throws Exception 
   {
      String candidate = "this is a test, A test.";
      String regex = "\\ba\\w*\\b";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(candidate);
      String val = null; 
      System.out.println("Input: " + candidate);
      System.out.println("Regex: " + regex + "\r\n");
      while (m.find()) 
      {
         val = m.group();
         System.out.println("Match: " + val);
      }
      if (val == null) 
      {
         System.out.println("No matches: ");
      }
   }
}

No comments:

Post a Comment