java中正则表达式匹配的一个例子。
jeval计算模块的参数有严格限制,只支持大小括号、小数点、数字、加减乘除符号。需要过滤掉不符合规则的字符。
String filter = "[0-9.+-/*/{}()]+"; boolean containOthers = "95/*{a.".matches(filter);
测试{}与()及^作用
public void testRegular() { String filter = "^#[A-Za-z0-9]{1,8}"; boolean f1 = "#C".matches(filter); boolean f2 = "A#".matches(filter); boolean f3 = "#Caaaaaaaaaaaaaa".matches(filter); boolean f4 = "#".matches(filter); boolean f5 = "#05sssaA".matches(filter); SysLog.v("f1=",f1,",f2=",f2,f3=",f3,f4=",f4,f5=",f5); String rgbFilter = "[0-9]{1,3},[0-9]{1,3}"; boolean d1 = "98".matches(rgbFilter); boolean d2 = "98,9,763".matches(rgbFilter); boolean d3 = ",99,97".matches(rgbFilter); boolean d4 = "a,08".matches(rgbFilter); SysLog.v("d1=",d1,d2=",d2,d3=",d3,d4=",d4); String ok = "([0-9],){3}"; boolean t1 = "9,".matches(ok); boolean t2 = "98,07,".matches(ok); boolean t3 = "9,8,7,".matches(ok); boolean t4 = "987".matches(ok); SysLog.v("t1=",t1,t2=",t2,t3=",t3,t4=",t4); }输出结果
f1=: true,f2= false,f3= false,f4= false,f5= true d1=: false,d2= true,d3= false,d4= false t1=: false,t2= false,t3= true,t4= false