我有以下模板字符串:"Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]"
。
我还有用于名称,发票编号和到期日的String变量-用变量替换模板中的标记的最佳方法是什么?
(请注意,如果变量恰好包含令牌,则不应将其替换)。
编辑
感谢@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();
}