java中Matcher类的find()和matches()的区别

        String str = "m222";
        Pattern p = Pattern.compile("[0-9]+");//0至9,出现一次或多次
        Matcher m = p.matcher(str);
        println("m.matches->>"+m.matches());//打印输出
        if(m.find()){
            println("m.find->>true");
            println("m.start->>"+m.start());
            println("m.end->>"+m.end());
            println("m.child->>"+str.substring(m.start(),m.end()));
        } else {
            println("m.find->>false");
        }

上面代码中用Pattern做了一个正则表达式p,然后用p去匹配str,最后得到匹配结果对象m。

m常用的方法有find()和matches()。这两个方法用于获取匹配结果,按照上方的代码输出结果会是这样

m.matches->>false
m.find->>true
m.start->>1
m.end->>4
m.child->>222

这时会有点疑惑,为什么matches方法返回了false,而find返回了true呢?

因为matches方法的匹配机制是针对整个字符串的,按照上面代码给出的正则表达式,如果想要通过matches方法返回true,则str必须全部是数字。

而find方法则不同,它属于搜索匹配。比如传入str="222m333",find方法会将这个字符串拆成若干个子字符串,只要有一个或多个子字符串符合正则表达式,则返回true。并且find方法还有类似于Map集合中next方法的功能。例如str=“222m333”时,第一次调用find方法,此时Matcher对象m的start值会为0、end值会为3。而再次调用时会start值会变成4、end值变成7。如果我们再调用一次find,就会直接返回false了。

这里贴一下find方法的源码

    /**
     * Attempts to find the next subsequence of the input sequence that matches
     * the pattern.
     *
     * <p> This method starts at the beginning of this matcher's region, or, if
     * a previous invocation of the method was successful and the matcher has
     * not since been reset, at the first character not matched by the previous
     * match.
     *
     * <p> If the match succeeds then more information can be obtained via the
     * {@code start}, {@code end}, and {@code group} methods.  </p>
     *
     * @return  {@code true} if, and only if, a subsequence of the input
     *          sequence matches this matcher's pattern
     */
    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);
    }

 

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值