问题

我有以下模板字符串:"Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]"

我还有名称,发票号和截止日期的字符串变量 - 用变量替换模板中的标记的最佳方法是什么?

(请注意,如果变量恰好包含令牌,则不应替换它)。
编辑
感谢@laginimaineb和@ alan-moore,这里是我的解决方案:

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

#1 热门回答(91 赞)

我真的认为你不需要使用模板引擎或类似的东西。你可以使用68882268方法,如下所示:

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

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

#2 热门回答(62 赞)

最有效的方法是使用匹配器不断查找表达式并替换它们,然后将文本附加到字符串构建器:

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(matcher.group(1));
    builder.append(text.substring(i, matcher.start()));
    if (replacement == null)
        builder.append(matcher.group(0));
    else
        builder.append(replacement);
    i = matcher.end();
}
builder.append(text.substring(i, text.length()));
return builder.toString();

#3 热门回答(39 赞)

你可以尝试使用像Apache Velocity这样的模板库。
http://velocity.apache.org/
这是一个例子:

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;

public class TemplateExample {
    public static void main(String args[]) throws Exception {
        Velocity.init();

        VelocityContext context = new VelocityContext();
        context.put("name", "Mark");
        context.put("invoiceNumber", "42123");
        context.put("dueDate", "June 6, 2009");

        String template = "Hello $name. Please find attached invoice" +
                          " $invoiceNumber which is due on $dueDate.";
        StringWriter writer = new StringWriter();
        Velocity.evaluate(context, writer, "TemplateName", template);

        System.out.println(writer);
    }
}

输出将是:

Hello Mark. Please find attached invoice 42123 which is due on June 6, 2009.

原文链接