java – 如何在没有StringTokenizer的字符串中替换令牌

给出一个像这样的字符串:
Hello {FIRST_NAME},this is a personalized message for you.

其中FIRST_NAME是任意令牌(传递给方法的地图中的一个键),要编写一个将该字符串变为:

Hello Jim,this is a personalized message for you.

给出了一个带有条目FIRST_NAME的地图 – >吉姆.

看起来StringTokenizer是最直接的方法,但Javadocs真的说你应该更喜欢使用正则表达式.您将如何在基于正则表达式的解决方案中执行此操作?

解决方法

尝试这个:

注意:author’s final solution建立在这个样本之上,更简洁.

public class TokenReplacer {

    private Pattern tokenPattern;

    public TokenReplacer() {
        tokenPattern = Pattern.compile("\\{([^}]+)\\}");
    }

    public String replaceTokens(String text,Map<String,String> valuesByKey) {
        StringBuilder output = new StringBuilder();
        Matcher tokenMatcher = tokenPattern.matcher(text);

        int cursor = 0;
        while (tokenMatcher.find()) {
            // A token is defined as a sequence of the format "{...}".
            // A key is defined as the content between the brackets.
            int tokenStart = tokenMatcher.start();
            int tokenEnd = tokenMatcher.end();
            int keyStart = tokenMatcher.start(1);
            int keyEnd = tokenMatcher.end(1);

            output.append(text.substring(cursor,tokenStart));

            String token = text.substring(tokenStart,tokenEnd);
            String key = text.substring(keyStart,keyEnd);

            if (valuesByKey.containsKey(key)) {
                String value = valuesByKey.get(key);
                output.append(value);
            } else {
                output.append(token);
            }

            cursor = tokenEnd;
        }
        output.append(text.substring(cursor));

        return output.toString();
    }

}

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...