java.util.regex Pattern的应用
1 public static void main(String[] args) { 2 //简单的正则匹配。从给定的字符串中匹配正则表达式 3 //匹配到返回true 匹配不到返回false 4 String regex_0 = "(\\;|\\?|\\'|\"|%)"; 5 String s="sx?fdfs'sd"; 6 Pattern pattern = Pattern.compile(regex_0); 7 Matcher matcher = pattern.matcher(s); 8 boolean as=matcher.find();//返回true 匹配到? 9 boolean dd=matcher.find();//返回true 匹配到' 10 boolean ss=matcher.find();//返回false 没有匹配到特殊符号 11 12 13 String regex_1=pattern.pattern();//返回当前匹配器的正则表达式 (\;|\?|\'|"|%) 14 String string=pattern.toString();//返回 (\;|\?|\'|"|%) 15 16 String regex_s="\\d+"; 17 boolean falg=Pattern.matches(regex_s,"897");//返回 true 18 19 20 String regex_2="(\\,)"; 21 String on="sxf,sxd,dong,leng"; 22 Pattern pattern2=Pattern.compile(regex_2); 23 String[] ad=pattern2.split(on);//[sxf, sxd, dong, leng] 24 25 String regex_3="([0-9]+)|(\\,)"; 26 String on2="sxf8sxs94sxy0df,hsl879dzq,xjt 45 "; 27 Pattern pattern3=Pattern.compile(regex_3); 28 String[] y=pattern3.split(on2);//[sxf, sxs, sxy, df, hsl, dzq, xjt , ] 29 String[] x=pattern3.split(on2,3);//[sxf, sxs, sxy0df,hsl879dzq,xjt 45 ](当3>0 匹配3-1次,数组长度不大于3,数组最后一个是除匹配到的剩余的串) 30 String[] z=pattern3.split(on2,9);//[sxf, sxs, sxy, df, hsl, dzq, xjt , ] 31 String[] h=pattern3.split(on2,-1);//[sxf, sxs, sxy, df, hsl, dzq, xjt , ](当第二个参数<0,匹配次数不受限制,数组长度为任意长度) 32 String[] m=pattern3.split(on2,0);//[sxf, sxs, sxy, df, hsl, dzq, xjt , ] 33 }