gpt4 book ai didi

java - Java 正则表达式中 matches() 和 find() 之间的区别

转载 作者:太空宇宙 更新时间:2023-11-04 09:35:14 28 4
gpt4 key购买 nike

我试图理解 matches() 之间的区别和find() .

根据Javadoc,(据我了解),matches() 将搜索整个字符串,即使它找到了它要查找的内容,而find() 将在找到它要查找的内容时停止。

如果这个假设是正确的,我看不到您何时想使用 matches() 而不是 find(),除非您想计算它找到的匹配项的数量。

在我看来,String 类应该有 find() 而不是 matches() 作为内置方法。

总结一下:

  1. 我的假设正确吗?
  2. 什么时候使用matches()而不是find()有用?

最佳答案

matches 尝试将表达式与整个字符串进行匹配,并在模式的开头隐式添加 ^ 并在模式末尾添加 $,这意味着它不会查找子字符串。因此这段代码的输出是:

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
*/

123a123b 的子字符串,因此 find() 方法输出 true。 matches() 仅“看到”a123b,它与 123 不同,因此输出 false。

关于java - Java 正则表达式中 matches() 和 find() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598817/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com