首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何替换Java字符串中的一组标记?

如何替换Java字符串中的一组标记?
EN

Stack Overflow用户
提问于 2009-06-06 14:00:28
回答 15查看 160.1K关注 0票数 113

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

我还有名称、发票编号和到期日的字符串变量--用这些变量替换模板中的令牌的最佳方法是什么?

(请注意,如果变量恰好包含令牌,则不应替换该变量)。

编辑

感谢@laginimaineb和@alan-moore,是我的解决方案:

代码语言:javascript
复制
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();
}
EN

回答 15

Stack Overflow用户

回答已采纳

发布于 2009-06-06 14:16:55

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

代码语言:javascript
复制
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();
票数 72
EN

Stack Overflow用户

发布于 2009-06-06 14:13:30

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

代码语言:javascript
复制
String template = "Hello %s Please find attached %s which is due on %s";

String message = String.format(template, name, invoiceNumber, dueDate);
票数 112
EN

Stack Overflow用户

发布于 2009-06-06 15:02:32

不幸的是,上面提到的舒适的方法String.format只有从Java1.5开始才可用(它现在应该是非常标准的,但你永远不会知道)。相反,您也可以使用Java的class MessageFormat来替换占位符。

它支持格式为'{number}‘的占位符,因此您的邮件将类似于“您好{0}请查找{1}附件{1},截止日期为{2}”。这些字符串可以很容易地使用ResourceBundles外部化(例如,用于多语言环境的本地化)。替换将使用类MessageFormat的静态‘’format‘方法完成:

代码语言:javascript
复制
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));
票数 49
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/959731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档