为什么我们在 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 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告