JDK8-正则匹配-String.matches坑

由于业务需求编写需要检测匹配获取字符串中的0的值的正则表达式,测试情况是没有问题的
在这里插入图片描述

代码一上死活都匹配不上,琢磨了半天

String regex = "[0][.][0][,]|[,][0][.][0][,]|[,][0][.][0]";
String string = "0.0,2.263,0.0,2.261,3.271,0.0";
System.out.println(string.matches(regex)); //返回false

随后我进入matches源码文档上已经作者已经写出使用该方法是检测字符串是否与正则表达式完全匹配
Tells whether or not this string matches the given(通知此字符串是否与给定的字符串匹配
在这里插入图片描述
按照方法的意思那么就是说我这个表达式只能匹配",0.0,“或"0.0,“或”,0.0”,果然测试如下

String regex = "[0][.][0][,]|[,][0][.][0][,]|[,][0][.][0]";
String string = ",0.0,";
System.out.println(string.matches(regex)); //返回true

我们需要对我们的正则表达式改进,1对()代表1种情况,别每种情况前后都需要加上匹配符号^/*/&

//3种情况
//(^[0][.][0][,].*) : 匹配"0"开头 内容"0.0," 在","后面匹配任意字符
//(.*[,][0][.][0][,].*) : 匹配","前面任意字符后面接着内容是",0.0,"在","后面匹配任意字符
//(.*[,][0][.][0]$) : 匹配","前面任意字符后面接着内容是",0.0"已"0"结尾的
String regex = "(^[0][.][0][,].*)|(.*[,][0][.][0][,].*)|(.*[,][0][.][0]$)";
String string = "0.0,2.263,0.0,2.261,3.271,0.0";
System.out.println(string.matches(regex)); //返回true

猜你喜欢

转载自blog.csdn.net/weixin_44642403/article/details/109553756