matches
try 将表达式与整个字符串匹配,并在模式的开头隐式添加^
,在模式的结尾隐式添加$
,这意味着它不会查找子字符串.因此,这段代码的输出是:
public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
123
是a123b
的子字符串,因此find()
方法输出true.matches()
只"看到"a123b
,这与123
不同,因此输出为假.