1. 程式人生 > 實用技巧 >Java正則表示式匹配的坑

Java正則表示式匹配的坑

今天在判斷字串是否存在某個字串,直接用String.matches(regex),死活匹配不出來,線上正則工具用了很多都是可以的,後面找到問題,總結一下,防止再次踩坑。

一、前提

java中判斷一段字串中是否包含某個字串的方式:

1、

String.matches(regex);

閱讀原始碼發現,這個方法本質是呼叫了Pattern.matches(regex, str),而該方法調Pattern.compile(regex).matcher(input).matches()方法,而Matcher.matches()方法試圖將整個區域與模式匹配,如果匹配成功,則可以通過開始、結束和組方法獲得更多資訊。

即這個方法會在表示式前後加上$(regex$),是對這個字串全匹配

而不會只匹配其中的子串,如果只想匹配子串,則需要表示式匹配整段

2、

Pattern.compile(regex).matcher(str).find()

Matcher.find()方法則是僅僅進行匹配字串的方法

如果不想使用全域性匹配則可以使用Matcher.find()方法

二、附原始碼

1、String.matches(regex)

String.matches(regex)

public boolean matches(String regex) {
        return Pattern.matches(regex, this);
}

Pattern.matches(regex, this)

public static boolean matches(String regex, CharSequence input) {
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(input);
    return m.matches();
}

2、Matcher.find()

Pattern.compile

public static Pattern compile(String regex) {
        return new Pattern(regex, 0);
}

Pattern.matcher

public Matcher matcher(CharSequence input) {
        if (!compiled) {
            synchronized(this) {
                if (!compiled)
                    compile();
            }
        }
        Matcher m = new Matcher(this, input);
        return m;
}

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

三、總結

各個匹配的優缺點都有,大家可以按需選擇

如果僅僅只需要獲取字串中是否包含某個字串,還是用Matcher.find()比較方便