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);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章