Tìm Duplicate word trong Regular Expression trong Java



Miêu tả vấn đề

Cách so khớp các Duplicate word trong một Regular Expression trong Java?

Giải pháp

Ví dụ sau minh họa cách tìm các Duplicate word trong một Regular Expression bởi sử dụng phương thức p.matcher() và m.group() của lớp regex.Matcher trong Java.

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

Kết quả

Code trên sẽ cho kết quả sau:

The string has matched with the pattern.

regular_expression_trong_java.jsp