java正则表达式中的坑String.matches(regex)、Pattern.matches(regex, str)和Matcher.matches()

版权声明:本文为博主原创文章,欢迎分享和转载。 https://blog.csdn.net/moakun/article/details/83187067

问题:程序会计算表达式的值

//将数值转换以K为单位
String value = "10*1000*1000";
String regex="\\s*\\*\\s*1000\\s*";
boolean isMatch = value .matches(regex);
if(isMatch){
   value = value.replaceFirst(regex,"");
}else{
   String[] nums = value.split("\\s*\\*\\s*");
   double val= Double.parseDouble(nums[0]);
   for(int i=1;i<nums.length;i++){
        val*=Double.parseDouble(nums[i]);
   }
   value = Double.toString(val/1000);
}
System.out.println(value);//10000.0

在百思不得其解的过程中,直到去查看了官方的文档,在找出原因。

String.matches(regex)方法本质调用了Pattern.matches(regex, str),而该方法调Pattern.compile(regex).matcher(input).matches()方法,而Matcher.matches()方法试图将整个区域与模式匹配,如果匹配成功,则可以通过开始、结束和组方法获得更多信息。

总的来说,String.matches(regex),Pattern.matches(regex, str),Matcher.matches()都是全局匹配的,相当于"^regex$"的正则匹配结果。如果不想使用全局匹配则可以使用Matcher.find()方法进行部分查找。

猜你喜欢

转载自blog.csdn.net/moakun/article/details/83187067
今日推荐