如何替换Java String中的一组标记? [英] How to replace a set of tokens in a Java String?

查看:116
本文介绍了如何替换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 String中的一组标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆