`
hgfghww5
  • 浏览: 45773 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
最近访客 更多访客>>
社区版块
存档分类
最新评论

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

 
阅读更多

  正则表达式中的替代操作和reset()方法
  import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author clydelou * */ public class RegexReplacement { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String str = " ZJU University in Zhejiang Province, China\n I love you!!!"; str = str.replaceAll("(?m)^ +", "");// 删除每行开头部分所有空格,(?m)打开多行状态,为使每一行都达到这个效果,而不仅仅只是删除文本开头部分的空格。 System.out.println(str); str = str.replaceAll(" {2,}", " ");// 将存在两个或者两个以上空格的地方,缩减为一个空格。 System.out.println(str); Pattern p = Pattern.compile("[aeiou]"); Matcher m = p.matcher(str); StringBuffer sbuf = new StringBuffer(); while (m.find()) { m.appendReplacement(sbuf, m.group().toUpperCase()); } m.appendTail(sbuf);// 将剩余未处理的部分复制到sbuf, // Implements a terminal append-and-replace step. // This method reads characters from the input sequence, starting at the // append position, and appends them to the given string buffer. It is // intended to be invoked after one or more invocations of the // appendReplacement method in order to copy the remainder of the input // sequence. System.out.println(sbuf.toString()); //reset()方法,可将现有的Matcher对象应用于一个新的字符序列 m=Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags"); while(m.find()) System.out.print(m.group()+"\t"); System.out.println(); m.reset("fix the rig with rags"); while(m.find()) System.out.print(m.group()+"\t"); System.out.println(); } }  运行结果:
  ZJU  University in Zhejiang  Province,      China
  I love you!!!
  ZJU University in Zhejiang Province, China
  I love you!!!
  ZJU UnIvErsIty In ZhEjIAng PrOvIncE, ChInA
  I lOvE yOU!!!
  fix    rug    bag    
  fix    rig    rag
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics