JAVA正则

10. JAVA正则

matcher.find()和matcher.matches()的区别

1. matches()

    功能:尝试根据模式匹配整个区域
    注意:匹配的是整个区域
    下面是测试源代码:
        //创建指定匹配规则的模型
        Pattern pattern = Pattern.compile("ab([1-8]*)f");
//创建匹配器
        Matcher matcher = pattern.matcher("ab5625836f");

        if(matcher.matches()) {
        System.out.println(matcher.start() + " " + matcher.end() + " " + matcher.group());
        } else {
        System.out.println("没有匹配到!");
        }
        输出结果:

        0 10 ab5625836f

2. find()

    功能:尝试查找与该模式匹配的输入序列的下一个子序列。
    
    注意:此方法从该匹配器区域的开始处开始,或者,如果该方法的前一次调用成功,匹配器也成功了,并且没有被重置,在上一次匹配成功后不能被匹配的第一个字符。
    
    下面是测试源代码:
        //创建指定匹配规则的模型
        Pattern pattern = Pattern.compile("ab([1-8]*)f");
//创建匹配器
        Matcher matcher = pattern.matcher("ab2fdsdfdfab348fdfab2333fddd");

        int count = 1;
        while (matcher.find()) {
        System.out.println("第" + count + "组: " + matcher.start() + " " + matcher.end() + " " + matcher.group());
        count ++;
        };
    输出结果:

    第1组: 0 4 ab2f
    第2组: 10 16 ab348f
    第3组: 18 25 ab2333f

3. 一种情况:单独使用find()可以查到,但在matches()之后使用find(),不能查到。

        //创建指定匹配规则的模型
        Pattern pattern = Pattern.compile("ab([1-8]*)f");
//创建匹配器
        Matcher matcher = pattern.matcher("ab5625836f");

        if(matcher.matches()) {
        System.out.println(matcher.start() + " " + matcher.end() + " " + matcher.group());
        } else {
        System.out.println("没有匹配到!");
        }

        if(matcher.find()){
        System.out.println(matcher.start() + " " + matcher.end() + " " + matcher.group());
        }
    find()方法源代码:
public boolean find() {
        int nextSearchIndex = last;
        if (nextSearchIndex == first)
        nextSearchIndex++;

        // If next search starts before region, start it at region
        if (nextSearchIndex < from)
        nextSearchIndex = from;

        // If next search starts beyond region then it fails
        if (nextSearchIndex > to) {
        for (int i = 0; i < groups.length; i++)
        groups[i] = -1;
        return false;
        }
        return search(nextSearchIndex);
        }
    注意第一句代码::int nextSearchIndex = last;

    在之前matches()执行后,last=10;所以nextSearchIndex从索引10开始查询,自然就查不到了。

4. 分组匹配

有如下需求:
字符串"<123abc>",其中开头结尾是<>固定格式,中间的内容前半部分是若干数字,后半部分是若干字母,要求分别获取出数字和字母。
在这里插入图片描述
关键在于正则表达式必须全局匹配成功才行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值