位置:首頁 > Java技術 > java實例教學 > Java搜索重複單詞

Java搜索重複單詞

如何在正則表達式匹配重複的單詞?

解決方法

下麵的示例演示如何使用regex.Matcher類的p.matcher()方法和m.group()方法來搜索正則表達式中重複的單詞。

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

結果

上麵的代碼示例將產生以下結果。

The string has matched with the pattern.