正则表达式中的替代操作和reset()方法

灰色的小熊 2012-07-06

正则表达式中的替代操作和reset()方法

importjava.util.regex.Matcher;importjava.util.regex.Pattern;/***@authorclydelou**/publicclassRegexReplacement{/***@paramargs*/publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubStringstr="ZJUUniversityinZhejiangProvince,China\nIloveyou!!!";str=str.replaceAll("(?m)^+","");//删除每行开头部分所有空格,(?m)打开多行状态,为使每一行都达到这个效果,而不仅仅只是删除文本开头部分的空格。System.out.println(str);str=str.replaceAll("{2,}","");//将存在两个或者两个以上空格的地方,缩减为一个空格。System.out.println(str);Patternp=Pattern.compile("[aeiou]");Matcherm=p.matcher(str);StringBuffersbuf=newStringBuffer();while(m.find()){m.appendReplacement(sbuf,m.group().toUpperCase());}m.appendTail(sbuf);//将剩余未处理的部分复制到sbuf,//Implementsaterminalappend-and-replacestep.//Thismethodreadscharactersfromtheinputsequence,startingatthe//appendposition,andappendsthemtothegivenstringbuffer.Itis//intendedtobeinvokedafteroneormoreinvocationsofthe//appendReplacementmethodinordertocopytheremainderoftheinput//sequence.System.out.println(sbuf.toString());//reset()方法,可将现有的Matcher对象应用于一个新的字符序列m=Pattern.compile("[frb][aiu][gx]").matcher("fixtherugwithbags");while(m.find())System.out.print(m.group()+"\t");System.out.println();m.reset("fixtherigwithrags");while(m.find())System.out.print(m.group()+"\t");System.out.println();}}运行结果:

ZJUUniversityinZhejiangProvince,China

Iloveyou!!!

ZJUUniversityinZhejiangProvince,China

Iloveyou!!!

ZJUUnIvErsItyInZhEjIAngPrOvIncE,ChInA

IlOvEyOU!!!

fixrugbag

fixrigrag

相关推荐