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()比较方便

posted @ 2020-08-19 18:27  MengW9  阅读(2666)  评论(1编辑  收藏  举报