Matcher AppendReplacement Token Swap

Expand template tokens with appendReplacement and appendTail: replacements are appended into a StringBuilder while group references stay intact.

JavaData Integrity

Code

snippet
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);
    }
}

What the code does

The working surface is the class TokenExpander and the function main — everything else is wiring.

Repetition is confined to while (matcher.find()) — the rest of the file is straight-line.

Statements that matter

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

Interactive Tools for This Topic

FAQ

How do you run Matcher AppendReplacement Token Swap?
It runs as-is — treat the file as the whole program and execute it.