Tutorials Point


  Java Basics Examples
  Java Tutorial
  Java Useful Resources
  Selected Reading

© 2011 TutorialsPoint.COM


  Home     References     Discussion Forums     About TP  

Java Examples - Searching Duplicate Words


previous next AddThis Social Bookmark Button


Problem Description:

How to match duplicate words in a regular expression?

Solution:

Following example shows how to search duplicate words in a regular expression by using p.matcher() method and m.group() method of regex.Matcher class.

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.");
   }
}

Result:

The above code sample will produce the following result.

The string has matched with the pattern.


previous next Printer Friendly



  

Advertisement

Online Image Processing

Indian Baby Names