String.matches() 与 Matcher.matches() 的区别

两者都可以实现正则表达式匹配,比如:

   public static boolean isNumber(String s){
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(s).matches();
    }

   public static boolean isNumber(String s){
        return s.matches("^[-\\+]?[.\\d]*$");
    }

好像都能得到同样的效果。而且查看String.matches()源码,实际上String.matches()内部也是调用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();
}

但两者还是有区别的。

如果你是对多个字符串进行匹配,那还是用Matcher.matches(),因为Pattern.compile()将正则表达式已经编译好,一次编译多次运行。而如果调用String.matches() ,则针对每个字符串都需要编译一下正则,即使正则表达式的内容都是一样的,效率会有些低。

比如上边的代码改成这样:

public static boolean isNumberAll(List list){
    Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
    for (String s : list) {
        if(!pattern.matcher(s).matches())  return false;          
    }
    return true;
}

当然Patter与Matcher的组合还有一些其他的功能,这里不细说。

你可能感兴趣的:(Java,SE)