正则匹配find与matches的区别

String string = "342中国";
String regex = "\\d*";    //  "^\\d*$"
if(string.matches(regex)){
    System.out.println("匹配");
}else {
    System.out.println("不匹配");
}

matches方法结果是不匹配

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(string);
if(m.find()){
    System.out.println("匹配");
}else{
    System.out.println("不匹配");
}

find方法结果是匹配

解释如下:

find()方法是部分匹配,是查找输入串中与模式匹配的子串,如果该匹配的串有组还可以使用group()函数。
matches()是全部匹配,是将整个输入串与模式匹配,如果要验证一个输入的数据是否为数字类型或其他类型,一般要用matches()。

find()对字符串进行匹配,匹配到的字符串可以在任何位置. 
Java代码示例: 
Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.find();//返回true 
Matcher m2=p.matcher("aa2223"); 
m2.find();//返回true 
Matcher m3=p.matcher("aa2223bb"); 
m3.find();//返回true 
Matcher m4=p.matcher("aabb"); 
m4.find();//返回false 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值