Java Regex中match()和find()之间的区别
我想明白之间的差别matches()和find()。
根据Javadoc,(据我了解),matches()即使找到了所要查找的内容,它也会搜索整个字符串,并find()在找到所要查找的内容时停止。
如果这个假设是正确的,我看不到,只要你想使用matches()的,而不是find(),除非你想指望它找到匹配的数量。
在我看来,String类应该具有find()而不是matches()作为内置方法。
总结一下:
- 我的假设正确吗?
- 什么时候
matches()代替有用find()?
回答:
matches尝试将表达式与整个字符串匹配,^并$在模式的开头和结尾隐式添加a ,这意味着它将不查找子字符串。因此,此代码的输出:
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,因此输出false。
以上是 Java Regex中match()和find()之间的区别 的全部内容, 来源链接: utcz.com/qa/407812.html
