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

Mark picture Mark · Jun 6, 2009 · Viewed 143.4k times · Source

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).


EDIT

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(matcher.group(1));
        if (replacement != null) {
            // matcher.appendReplacement(buffer, replacement);
            // see comment 
            matcher.appendReplacement(buffer, "");
            buffer.append(replacement);
        }
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

Answer

Paul Morie picture Paul Morie · Jun 6, 2009

I really don't think you need to use a templating engine or anything like that for this. You can use the String.format method, like so:

String template = "Hello %s Please find attached %s which is due on %s";

String message = String.format(template, name, invoiceNumber, dueDate);