加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:20:19 所属栏目:Java 来源:网络整理
导读:给出一个像这样的字符串: Hello {FIRST_NAME},this is a personalized message for you. 其中FIRST_NAME是任意令牌(传递给方法的地图中的一个键),要编写一个将该字符串变为: Hello Jim,this is a personalized message for you. 给出了一个带有条目FIRST_N
给出一个像这样的字符串:
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();
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读