為什麼我們在 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 年 6 月 21 日

987 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.