正则表达式中的替代操作和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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值