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<String> list){
    Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
    for (String s : list) {
        if(!pattern.matcher(s).matches())  return false;          
    }
    return true;
}

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值