Java Matcher.matches() 和 Matcher.find()
Matcher.matches()
Matcher.matches()
方法检查整个输入字符串是否完全符合指定的正则表达式模式。如果整个字符串完全匹配,则返回 true
;否则返回 false
。
示例代码
String input = "123-456-7890";
Pattern pattern = Pattern.compile("^\\d{3}-\\d{3}-\\d{4}$");
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println(true);
} else {
System.out.println(false);
}
输出结果:true
注意事项
matches()
要求整个字符串与正则表达式完全匹配。- 该方法通常用于验证输入格式,例如邮箱、电话号码等。
Matcher.find()
与 Matcher.matches()
Matcher.find()
方法用于在输入字符串中查找与正则表达式匹配的子串。如果找到匹配项,则返回 true
;否则返回 false
。当 find()
方法成功找到一个匹配时,我们可以使用 group()
方法来获取具体的匹配结果。
交互影响
值得注意的是,Matcher.matches()
和 Matcher.find()
之间存在一定的交互影响。具体来说,在同一 Matcher
对象上调用 matches()
并返回 true
后,再调用 find()
会导致 find()
返回 false
,即使在理论上字符串中还存在其他的匹配子串。
示例代码
String input = "123-456-7890";
Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
Matcher matcher = pattern.matcher(input);
// 先尝试使用 matches()
if (matcher.matches()) {
System.out.println(true);
} else {
System.out.println(false);
}
// 再尝试使用 find()
if (matcher.find()) {
System.out.println("Found a match: " + matcher.group());
} else {
System.out.println("No match found.");
}
运行结果:
true
No match found.
在这个例子中,matches()
检查整个字符串是否符合正则表达式的模式,而 find()
查找任何匹配的子串。当 matches()
返回 true
时,表示整个字符串符合模式,但此时 find()
不会返回 true
,即使字符串中还有其他符合模式的子串。
注意事项
- 当先调用
matches()
且返回true
时,再调用find()
,其结果总是false
。 - 这是因为
matches()
成功后改变了Matcher
对象的状态,导致后续的find()
不再能找到新的匹配。
结论
当需要验证整个字符串是否完全匹配某个模式时,应使用 matches()
。而在需要查找字符串中的任意匹配子串时,则应该使用 find()
。如果你需要在调用 matches()
后继续使用 find()
,请确保创建一个新的 Matcher
对象或进行重置matcher.reset()
。
参考链接: