java 29 lines · 8 steps

Rendering ${} templates with regex in Java

A small utility that swaps ${key} placeholders for map values, failing loudly on anything missing.

Explained by highlit
1import java.util.Map;
2import java.util.regex.Matcher;
3import java.util.regex.Pattern;
4 
5public final class TemplateRenderer {
6 
7 private static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{([a-zA-Z0-9_.]+)\\}");
8 
9 private TemplateRenderer() {
10 }
11 
12 public static String render(String template, Map<String, ?> values) {
13 Matcher matcher = PLACEHOLDER.matcher(template);
14 StringBuilder out = new StringBuilder();
15 
16 while (matcher.find()) {
17 String key = matcher.group(1);
18 if (!values.containsKey(key)) {
19 throw new IllegalArgumentException("Missing value for placeholder: " + key);
20 }
21 Object value = values.get(key);
22 String replacement = value == null ? "" : value.toString();
23 matcher.appendReplacement(out, Matcher.quoteReplacement(replacement));
24 }
25 
26 matcher.appendTail(out);
27 return out.toString();
28 }
29}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Compiling a Pattern once as a static field avoids rebuilding it on every render call.
  2. 2The appendReplacement/appendTail pair lets you rewrite matches while copying untouched text verbatim.
  3. 3quoteReplacement neutralizes $ and backslash in substituted values so user data can't corrupt the output.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Rendering ${} templates with regex in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code