我有以下模板字符串:"Hello [Name] Please find attached [Invoice Number] which is due to [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();
}
最佳答案
我真的认为您不需要为此使用模板引擎或类似的东西。您可以使用 String.format
方法,像这样:
String template = "Hello %s Please find attached %s which is due on %s";
String message = String.format(template, name, invoiceNumber, dueDate);
关于java - 如何替换 Java 字符串中的一组标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/959731/