← 中文资源

简体中文版本

Matcher appendReplacement 令牌替换

appendReplacement 边扫边把原文与展开结果写进 StringBuilder,appendTail 收尾;$1 引用捕获组,任意值用 quoteReplacement 免去符号转义。

阅读英文原文

实现说明

Matcher appendReplacement 令牌替换的核心是类 TokenExpander和函数 main。 驱动整个流程的是 while (matcher.find()) 这一个循环。

常见问题

「Matcher appendReplacement 令牌替换」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

核心语句

matcher.appendReplacement(out, "$1=" + Matcher.quoteReplacement(value));
static final Pattern TOKEN = Pattern.compile("\\{([a-z_]+)\\}");
String template = "deploy ${user} to ${region} as ${user}";

代码示例

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TokenExpander {

    static final Pattern TOKEN = Pattern.compile("\\{([a-z_]+)\\}");
    static final Map<String, String> VALUES =
            Map.of("user", "ada", "region", "eu-central-1");

    public static void main(String[] args) {
        String template = "deploy ${user} to ${region} as ${user}";
        Matcher matcher = TOKEN.matcher(template);
        StringBuilder out = new StringBuilder();

        // appendReplacement 把匹配前的原文 + 展开结果追加进 buffer
        while (matcher.find()) {
            String value = VALUES.getOrDefault(matcher.group(1), "?");
            // 1 号组引用;替换串里的特殊符号交给 quoteReplacement 处理
            matcher.appendReplacement(out, "$1=" + Matcher.quoteReplacement(value));
        }
        // appendTail 收尾:最后一段未匹配文本
        matcher.appendTail(out);

        System.out.println(out);
    }
}