在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