更新时间:2023-01-14 20:53:09
匹配
尝试将表达式与整个字符串匹配,并隐式添加 ^
在开头, $
在模式的末尾,这意味着它不会查找子字符串。因此这段代码的输出:
matches
tries to match the expression against the entire string and implicitly add a ^
at the start and $
at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:
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 $的子字符串c $ c>所以
find()
方法输出为true。 matches()
只有'看' a123b
这与 123 $不同c $ c>因此输出错误。
123
is a substring of a123b
so the find()
method outputs true. matches()
only 'sees' a123b
which is not the same as 123
and thus outputs false.