正则表达式在进行一些字符串的处理中应用很广,前几天了解了一下java正则相关的一些api,弄几个小栗子记录一下。
1、进行字符匹配,这个应该是正则最伟大的地方了吧
public void test1(){ Pattern pattern=Pattern.compile("^\\d{4}[A-Za-z]*$"); Matcher matcher=pattern.matcher("3243fdsfd"); System.out.println(matcher.matches());//true }
2、分割字符串,这个功能也挺强大的
public void test2(){ Pattern pattern = Pattern.compile("[, |]+"); String[] strs = pattern.split("abcd|12321,,fj"); for (int i=0;i<strs.length;i++) { System.out.println(i+"========"+strs[i]); //abcd,12321,fj } }
当然,String的split()方法本身也是支持的
public void test3(){ String str = "fdsf|sfd,s"; String []strArray = str.split("[|,]+") ; for(String temp:strArray){ System.out.println(temp);//fdsf,sfd,s } }
3、按字符替换
public void test4(){ Pattern pattern = Pattern.compile("\\d{3}|Hell"); Matcher matcher = pattern.matcher("dfsdf123fdsfdHelle"); StringBuffer sbr = new StringBuffer(); while (matcher.find()) { System.out.println(matcher.group());//获取匹配的字符串,这个方法比较好用,可以用来做动态匹配 matcher.appendReplacement(sbr, "Java"); System.out.println(sbr.toString()); } matcher.appendTail(sbr); System.out.println(sbr.toString()); }
4、替换指定正则字符
public void test5(){ Pattern pattern = Pattern.compile("\\d{3}"); Matcher matcher = pattern.matcher("3213 Hello World,Hellfdsaf323o World"); System.out.println(matcher.replaceAll("yyy"));//全部替换为yyy }
对应String相关api
public void test6(){ String tt="fdjskaf234fdsj432jk444"; System.out.println(tt.replaceAll("\\d{3}", "009")); System.out.println(tt.replaceFirst("\\d{3}", "009")); }
大概就这些吧、mark一下、