What's the difference between String.matches and Matcher.matches?

后端 未结 5 1783
生来不讨喜
生来不讨喜 2020-12-08 13:11

What\'s the difference between String.matches and Matcher.matches? Is there any difference in terms of performance or other things?

5条回答
  •  一整个雨季
    2020-12-08 13:55

    String.matches internally delegates to Matcher.matches.

    public boolean matches(String regex) {
        return 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();
    }
    

    If you are reusing the Pattern object then there will be some performance benefit. Also when using Pattern/Matcher you can group your regular expressions and get the matching parts.

    The bottomline is if you have a regex that you will use only once and you don't need to parse your string to get matching parts then use either. But if you are going to use the same regex against multiple strings or you need parts of the String based on regex create a Pattern and get Matcher using it.

提交回复
热议问题