利用Java的Pattern类,进行正则匹配数字,小数,精度控制到两位小数,区间表达式的正确性
上代码:
public static void main(String[] args) {
String sn1 = "1.";
String sn2 = "1.23";
String sn3 = "111.333";
String sn4 = "0.2";
String sn5 = "1.222222";
String s1 = "(0.11,0.]";
String s2 = "[-1,2.222]";
String s3 = "(1.11,02.22)";
String s4 = "[0,2.2)";
String numP = "(-?[1-9]+(.[0-9]{1,2})?)|(-?[1-9][0-9]+(.[0-9]{1,2})?)|(-?0(.[0-9]{1,2})?)"; //小数点后两位小数
String numP2 = "(-?[1-9]+(.[0-9]+)?)|(-?[1-9][0-9]+(.[0-9]+)?)|(-?0(.[0-9]+)?)"; //小数点后多位小数
String betweenP = "^(\\(|\\[)((-?[1-9]+(.[0-9]{1,2})?)|(-?[1-9][0-9]+(.[0-9]{1,2})?)|(-?0(.[0-9]{1,2})?)),((-?[1-9]+(.[0-9]{1,2})?)|(-?[1-9][0-9]+(.[0-9]{1,2})?)|(-?0(.[0-9]{1,2})?))(\\)|\\])$";//小数点后两位小数区间表达式
Pattern p = Pattern.compile(numP);
Pattern p2 = Pattern.compile(betweenP);
Pattern p3 = Pattern.compile(numP2);
Matcher mn1 = p.matcher(sn1);
Matcher mn2 = p.matcher(sn2);
Matcher mn3 = p.matcher(sn3);
Matcher mn4 = p.matcher(sn4);
Matcher m1 = p2.matcher(s1);
Matcher m2 = p2.matcher(s2);
Matcher m3 = p2.matcher(s3);
Matcher m4 = p2.matcher(s4);
Matcher m5 = p3.matcher(sn5);
Matcher m6 = p.matcher(sn5);
System.out.println(mn1.matches());
System.out.println(mn2.matches());
System.out.println(mn3.matches());
System.out.println(mn4.matches());
System.out.println(m1.matches());
System.out.println(m2.matches());
System.out.println(m3.matches());
System.out.println(m4.matches());
System.out.println(m5.matches());
System.out.println(m6.matches());
}