热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

用java替换字符串中所有标签的最佳方法-bestwayofreplacingalltagsinastringwithjava

IhaveaservicemethodthattakesaStringandthenreplacestagsintheStringwithitemsfromat

I have a service method that takes a String and then replaces tags in the String with items from a tag library. As follows:

我有一个服务方法,它接受一个String,然后用标签库中的项替换String中的标签。如下:

for( MetaDataDTO tag : tagValues )
{
    message = message.replace( tag.getKey(), tag.getText1() );
}

Obviously; this make heaps of new strings and is BAD. But the StringBuilder replace method is cumbersome to use for multiple strings inside one string. How can I make my method more efficient?

明显;这使得大量的新字符串变得糟透了。但StringBuilder替换方法对于一个字符串中的多个字符串使用是很麻烦的。如何使我的方法更有效?

It is for use with blocks of text such as:

它适用于文本块,例如:

Dear #firstName#, your application for #applicationType# has been #approvedRejected# sorry.

亲爱的#firstName#,#applicationType#的申请已被#approvedRejected#sorry。

Where #firstName#, etc are the keys in a meta data database. It is also possible that tags may not be surrounded by hash characters.

其中#firstName#等是元数据数据库中的键。标签也可能不被散列字符包围。

2 个解决方案

#1


Basically you want to copy the execution of Matcher.replaceAll() like so:

基本上你想复制Matcher.replaceAll()的执行,如下所示:

public static String replaceTags(String message, Map tags) {
  Pattern p = Pattern.compile("#(\\w+)#");
  Matcher m = p.matcher(message);
  boolean result = m.find();
  if (result) {
    StringBuffer sb = new StringBuffer();
    do {
      m.appendReplacement(sb, tags.containsKey(m.group(1) ? tags.get(m.group(1)) : "");
      result = m.find();
    } while (result);
    m.appendTail(sb);
    message = sb.toString();
  }
  return message;
}

Note: I've made an assumption about the valid tag (namely \w in the regex). You will need to cater this for what's really valid (eg "#([\w_]+)#").

注意:我已经假设有效标记(即正则表达式中的\ w)。你需要为真正有效的东西提供这个(例如“#([\ w _] +)#”)。

I've also assumed the tags above looks something like:

我还假设上面的标签看起来像:

Map tags = new HashMap();
tags.add("firstName", "Skippy");

and not:

tags.add("#firstName#", "Skippy");

If the second is correct you'll need to adjust accordingly.

如果第二个是正确的,您需要相应调整。

This method makes exactly one pass across the message string so it doesn't get much more efficient than this.

这种方法只对消息字符串进行一次传递,因此它不会比这更有效。

#2


Thanks for your help guys. Certainly learned more about java. Here is my solution. It is this way to support different looking tags and tags within tags:

谢谢你的帮助。当然更多地了解了java。这是我的解决方案。这种方式可以支持标签中不同的标签和标签:

private static String replaceAllTags(String message, Map tags)
{
    StringBuilder sb = new StringBuilder( message );
    boolean tagFound = false;
    /**
     * prevent endless circular text replacement loops
     */
    long recurrancyChecker = 5000;

    do
    {
        tagFound = false;
        Iterator it = tags.entrySet().iterator();
        while( it.hasNext() )
        {
            Map.Entry pairs = (Map.Entry) it.next();

            int start = sb.indexOf( pairs.getKey().toString() );

            while( start > -1 && --recurrancyChecker > 0 )
            {
                int length = pairs.getKey().toString().length();
                sb.replace( start, start + length, pairs.getValue().toString() );
                start = sb.indexOf( pairs.getKey().toString() );
                tagFound = true;
            }
        }
    }
    while( tagFound && --recurrancyChecker > 0 );
    return sb.toString();
}

推荐阅读
author-avatar
符小萧_103
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有