我有以下模板字符串:"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();
}
发布于 2009-06-06 14:16:55
最有效的方法是使用匹配器不断地查找表达式并替换它们,然后将文本附加到字符串构建器:
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();
发布于 2009-06-06 14:13:30
我真的不认为你需要使用模板引擎或任何类似的东西。您可以使用String.format
方法,如下所示:
String template = "Hello %s Please find attached %s which is due on %s";
String message = String.format(template, name, invoiceNumber, dueDate);
发布于 2009-06-06 15:02:32
不幸的是,上面提到的舒适的方法String.format只有从Java1.5开始才可用(它现在应该是非常标准的,但你永远不会知道)。相反,您也可以使用Java的class MessageFormat来替换占位符。
它支持格式为'{number}‘的占位符,因此您的邮件将类似于“您好{0}请查找{1}附件{1},截止日期为{2}”。这些字符串可以很容易地使用ResourceBundles外部化(例如,用于多语言环境的本地化)。替换将使用类MessageFormat的静态‘’format‘方法完成:
String msg = "Hello {0} Please find attached {1} which is due on {2}";
String[] values = {
"John Doe", "invoice #123", "2009-06-30"
};
System.out.println(MessageFormat.format(msg, values));
https://stackoverflow.com/questions/959731
复制相似问题