我們為什麼要在 Java 正則表示式中使用完整字串


在 Java 中,正則表示式 matches() 函式將輸入字串與整個字串進行匹配,因為它在輸入字串的末尾添加了 ^ 和 $。因此,它不會匹配子字串。因此,要匹配子字串,應使用 find() 函式。

示例

import java.util.regex.*;
class PatternMatchingExample {
   public static void main(String args[]) {
      String content = "aabbcc";
      String string = "aa";
      Pattern p = Pattern.compile(string);
      Matcher m = p.matcher(content);
      System.out.println(" 'aa' Match:"+ m.matches());
      System.out.println(" 'aa' Match:"+ m.find());
   }
}

輸出

'aa' Match:false
'aa' Match:true

更新時間:2020-06-21

985 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.