Mark Mark - 2 months ago 14x
Java Question

How to replace a set of tokens in a Java String?

I have the following template String:

"Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]"

I also have String variables for name, invoice number and due date - what's the best way to replace the tokens in the template with the variables?

(Note that if a variable happens to contain a token it should NOT be replaced).


With thanks to @laginimaineb and @alan-moore, here's my solution:

public static String replaceTokens(String text,
Map<String, String> replacements) {
Pattern pattern = Pattern.compile("\\[(.+?)\\]");
Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();

while (matcher.find()) {
String replacement = replacements.get(;
if (replacement != null) {
// matcher.appendReplacement(buffer, replacement);
// see comment
matcher.appendReplacement(buffer, "");
return buffer.toString();


The most efficient way would be using a matcher to continually find the expressions and replace them, then append the text to a string builder:

Pattern pattern = Pattern.compile("\\[(.+?)\\]");
Matcher matcher = pattern.matcher(text);
HashMap<String,String> replacements = new HashMap<String,String>();
//populate the replacements map ...
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
    String replacement = replacements.get(;
    builder.append(text.substring(i, matcher.start()));
    if (replacement == null)
    i = matcher.end();
builder.append(text.substring(i, text.length()));
return builder.toString();