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

Mar*_*ark 1 java string stringbuilder replace

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

for( MetaDataDTO tag : tagValues )
{
    message = message.replace( tag.getKey(), tag.getText1() );
}
Run Code Online (Sandbox Code Playgroud)

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

它用于文本块,例如:

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

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

cle*_*tus 9

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

public static String replaceTags(String message, Map<String, String> 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Map<String, String> tags = new HashMap<String, String>();
tags.add("firstName", "Skippy");
Run Code Online (Sandbox Code Playgroud)

并不是:

tags.add("#firstName#", "Skippy");
Run Code Online (Sandbox Code Playgroud)

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

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