replaceAll ()/appendReplacement()/appendTail():

 

★ replaceAll ()/appendReplacement()/appendTail():
Matcher 类同时提供了四个将匹配子串替换成指定字符串的方法:

  1. replaceAll()
  2. replaceFirst()
  3. appendReplacement()
  4. appendTail()


public class Test {
 
 /**
  * @param args
  * @return
  * 4
  * 1240
  * 124067
  */
 public static void main(String[] args) {
  String string="1234567";
  Matcher matcher = Pattern.compile("3(4)5").matcher(string);
  if(matcher.find()){
   System.out.println(matcher.group(1));
   StringBuffer sb = new StringBuffer();
   matcher.appendReplacement(sb, matcher.group(1)+"0");  //替换的是整个group()

   matcher.appendReplacement(sb, "$0"+"$1"+"_recycle/");

   System.out.println(sb);
   matcher.appendTail(sb);
   System.out.println(sb.toString());
   
  }
 }

}

 

replaceAll() 与 replaceFirst() 的用法都比较简单,请看上面方法的解释。我们主要重点了解一下 appendReplacement() 和 appendTail() 方法。

appendReplacement(StringBuffer sb, String replacement) 将当前匹配子串替换为指定字符串,并且将替换后的子串以及其之前到上次匹配子串之后的字符串段添加到一个 StringBuffer 对象里,而 appendTail(StringBuffer sb) 方法则将最后一次匹配工作后剩余的字符串添加到一个 StringBuffer 对象里。

例如,有字符串 fatcatfatcatfat, 假设既有正则表达式模式为"cat",第一次匹配后调用 appendReplacement(sb,"dog"), 那么这时 StringBuffer sb 的内容为 fatdog,也就是 fatcat 中的 cat 被替换为 dog 并且与匹配子串前的内容加到 sb 里,而第二次匹配后调用 appendReplacement(sb,"dog"),那么 sb 的内容就变为 fatdogfatdog,如果最后再调用一次 appendTail(sb), 那么 sb 最终的内容将是 fatdogfatdogfat。

还是有点模糊?那么我们来看个简单的程序:

 // 该例将把句子里的"Kelvin"改为"Kevin"
 import java.util.regex.*; 
 public class MatcherTest{ 
    public static void main(String[] args) 
                         throws Exception { 
        // 生成 Pattern 对象并且编译一个简单的正则表达式"Kelvin"
        Pattern p = Pattern.compile("Kevin"); 
        // 用 Pattern 类的 matcher() 方法生成一个 Matcher 对象
        Matcher m = p.matcher("Kelvin Li and Kelvin Chan are both working in " +
			"Kelvin Chen's KelvinSoftShop company"); 
        StringBuffer sb = new StringBuffer(); 
        int i=0; 
        // 使用 find() 方法查找第一个匹配的对象
        boolean result = m.find(); 
        // 使用循环将句子里所有的 kelvin 找出并替换再将内容加到 sb 里
        while(result) { 
            i++; 
            m.appendReplacement(sb, "Kevin"); 
            System.out.println("第"+i+"次匹配后 sb 的内容是:"+sb); 
            // 继续查找下一个匹配对象
            result = m.find(); 
        } 
        // 最后调用 appendTail() 方法将最后一次匹配后的剩余字符串加到 sb 里;
        m.appendTail(sb); 
        System.out.println("调用 m.appendTail(sb) 后 sb 的最终内容是 :"+ 
			sb.toString());
    } 
 }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值