m.appendReplacement(String a,String b)使用记录

在看flume源码时遇到 m.appendReplacement(String a,String b)函数,一时没看懂,仔细看了一下。

public class RegexDemo02 {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("cat");
        Matcher m = p.matcher("one cat two cats in the yard");
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, "dog");
        }
        m.appendTail(sb);
        System.out.println(sb.toString());
    }

}
  • 主要功能就是将正则表达式匹配成功的替换成dog,

/appendReplacement函数的功能

//将从上一次匹配成功的下一个位置还有这一个匹配成功的开始的上一次位置+这一次匹配的字符串

//text:为匹配器赋予的原始文本也就是待匹配文本

//lastAppendPosition:上一次追加的位置,第一次为0

//first:这一个匹配成功的开始位置

//将原始文本的从上一次匹配成功的最后位置到这次匹配成功开始的位置追加到sb

//例如text: one cat two cats in the yard lastAppendPosition:0 first:4 res:"one "

sb.append(text, lastAppendPosition, first);

//在将匹配上的字符串处理后再追加到sb后面

sb.append(result);

//这下最后追加的位置就是这个匹配成功的最后的位置

lastAppendPosition = last;

讲的不是很清楚,自己debug代码就可以了。

猜你喜欢

转载自my.oschina.net/112612/blog/1810178