Matcher AppendReplacement Token Swap
Expand template tokens with appendReplacement and appendTail: replacements are appended into a StringBuilder while group references stay intact.
Code
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
URL Pattern MatcherTest Express-style URL patterns with :param and wildcard segments against concrete paths and extract the captured parameter values.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.
FAQ
- How do you run Matcher AppendReplacement Token Swap?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.