如何替换 Java 字符串中的一组标记? [英] How to replace a set of tokens in a Java String?
问题描述
我有以下模板字符串:你好 [姓名] 请找到附件中的 [发票号码],它在 [截止日期] 到期"
.
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).
编辑
感谢@laginimaineb 和@alan-moore,这是我的解决方案:
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();
}
推荐答案
最有效的方法是使用匹配器不断查找表达式并替换它们,然后将文本附加到字符串生成器:
The most efficient way would be using a matcher to continually find the expressions and replace them, then append the text to a string builder:
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();
这篇关于如何替换 Java 字符串中的一组标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!