栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA正则

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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开始查询,自然就查不到了。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/666813.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号