Java Matcher.matches() 和 Matcher.find()

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()

参考链接:

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值