我们为什么要在 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.