Matcher.appendReplacement(StringBuffer sb, String replacement)解析

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());

//appendReplacement函数的功能
//将从上一次匹配成功的下一个位置还有这一个匹配成功的开始的上一次位置+这一次匹配的字符串
//第一次匹配成功的最后一个的位置是-1
//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;

原文地址:https://www.cnblogs.com/xushihai/p/4165739.html