美文网首页
Matcher的replaceAll ()/appendRepl

Matcher的replaceAll ()/appendRepl

作者: _FireFly_ | 来源:发表于2019-07-24 22:18 被阅读0次

    Matcher的replaceAll ()/appendReplacement()/appendTail()详细举例

    直接上例子:

    package com.dajiangtai.djt_spider.util;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class MatcherTest {
    public static void main(String[] args)
    throws Exception {
    //生成Pattern对象并且编译一个简单的正则表达式"Kelvin"
    Pattern p = Pattern.compile("Kelvin");
    //用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());
    }
    
    
    }
    

    输出:

    第1次匹配后sb的内容是:Kevin
    第2次匹配后sb的内容是:Kevin Li and Kevin
    第3次匹配后sb的内容是:Kevin Li and Kevin Chan are both working in Kevin
    第4次匹配后sb的内容是:Kevin Li and Kevin Chan are both working in Kevin Chen's Kevin
    调用m.appendTail(sb)后sb的最终内容是:Kevin Li and Kevin Chan are both working in Kevin Chen's KevinSoftShop company

    用法说明:

    String replaceAll(String replacement)

    将目标字符串里与既有模式相匹配的子串全部替换为指定的字符串。

    String replaceFirst(String replacement)

    将目标字符串里第一个与既有模式相匹配的子串替换为指定的字符串。

    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。

    相关文章

      网友评论

          本文标题:Matcher的replaceAll ()/appendRepl

          本文链接:https://www.haomeiwen.com/subject/fqlqrctx.html