问题:程序会计算表达式的值
//将数值转换以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()方法进行部分查找。