正则表达式 matcher.find() 一直为true

Java 正则表达式 matcher.find() 一直为true

 

知识点:

*

匹配前面的子表达式零次或多次。要匹配 * 字符,请使用 \*

+

匹配前面的子表达式一次或多次。要匹配 + 字符,请使用 \+

 

matches(): 全匹配 为true

find(): 部分匹配 为true

 

判断字符串中是否有数字

判断字符串中是否有数字

 String str2 = "curStaff[].staffId(\"12\").staffName"; 

表达式:

  String regExp =  "[0-9]*";

 

 

代码:

public static void main(String[] args) {
    testNums();
}

public static void testNums(){
    String str2 = "1aa564sdfp5324";
    System.out.println("======= "+str2+" =========");
    hasDigit(str2);
    str2 = "234564";
    System.out.println("======= "+str2+" =========");
    hasDigit(str2);
    str2 = "asdfasdfa";
    System.out.println("======= "+str2+" =========");
    hasDigit(str2);
    str2 = "curStaff[33].staffId(\"12yan\").staffName12";
    System.out.println("======= "+str2+" =========");
    hasDigit(str2);
}

public static boolean hasDigit(String content) {
    String regExp =  "[0-9]*";
    Pattern pattern=Pattern.compile(regExp);
    Matcher m = pattern.matcher(content);
    System.out.println(" matches nums: " +m.matches());
    System.out.println(" find nums: " +m.find());
    return m.find();
}

结果:

======= 1aa564sdfp5324 =========
 matches nums: false
 find nums: true
======= 234564 =========
 matches nums: true
 find nums: true
======= asdfasdfa =========
 matches nums: false
 find nums: true
======= curStaff[33].staffId("12yan").staffName12 =========
 matches nums: false
 find nums: true

find 都为true, 为啥呢? 再看表达式 String regExp =  "[0-9]*"; * 可以为0次,所以出问题了。

把“*”改成“+”: String regExp =  "[0-9]+";

 

结果:

======= 1aa564sdfp5324 =========
 matches nums: false
 find nums: true
======= 234564 =========
 matches nums: true
 find nums: false
======= asdfasdfa =========
 matches nums: false
 find nums: false
======= curStaff[33].staffId("12yan").staffName12 =========
 matches nums: false
 find nums: true

这样就达到目标了。

 

总结:

  在写正则表达的时候要注意细节,比如匹配数字的时候,至少要存在一次,这时候得用“+”,用“*”就会出问题。如果出现了差错,就看下表达式中相关语法具体的含义,这样就能快速定位到问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天狼1222

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值