/**
* 替换上下文
*
* @author tianhongjun
*
*/
static class EvaluateContext {
private int startPos;
private int endPos;
private String replacement;
}
public interface IEvaluator {
String evaluate(String[] groups);
}
/**
* 正则替换
*
* @param src 原始字符串
* @param regex 替换正则
* @param replacer 替换器(根据匹配的内容不同返回不同的替换值,类似模板替换)
* @return
*/
public static String replace(final String src, final Pattern regex, IEvaluator replacer) {
final Matcher m = regex.matcher(src);
// 先查询匹配
List<EvaluateContext> ctxs = new ArrayList<>();
while (m.find()) {
// 记录所有匹配的位置 & 匹配结果
EvaluateContext ctx = new EvaluateContext();
ctx.startPos = m.start();
ctx.endPos = m.end();
// System.out.println("grp count = " + m.groupCount());
String[] groups = new String[m.groupCount() + 1];
groups[0] = m.group();
for (int i = 0; i < m.groupCount(); i++) {
groups[i + 1] = m.group(i + 1);
}
ctx.replacement = replacer.evaluate(groups);
ctxs.add(ctx);
}
// 再进行替换
List<String> parts = new ArrayList<>();
int sp = 0;
for (EvaluateContext ctx : ctxs) {
if (sp < ctx.startPos) {
parts.add(src.substring(sp, ctx.startPos));
}
parts.add(ctx.replacement);
sp = ctx.endPos;
}
// 结尾补齐
if (sp < src.length()) {
parts.add(src.substring(sp));
}
StringBuilder sb = new StringBuilder();
for (String s : parts) {
sb.append(s);
}
return sb.toString();
}