简体   繁体   English

如何在没有StringTokenizer的情况下替换字符串中的标记

[英]How to replace tokens in a string without StringTokenizer

Given a string like so: 给出一个像这样的字符串:

 Hello {FIRST_NAME}, this is a personalized message for you.

Where FIRST_NAME is an arbitrary token (a key in a map passed to the method), to write a routine which would turn that string into: FIRST_NAME是一个任意标记(传递给方法的地图中的一个键),编写一个例程,将该字符串转换为:

Hello Jim, this is a personalized message for you.

given a map with an entry FIRST_NAME -> Jim. 给出了一张带有FIRST_NAME条目的地图 - > Jim。

It would seem that StringTokenizer is the most straight forward approach, but the Javadocs really say you should prefer to use the regex aproach. 似乎StringTokenizer是最直接的方法,但Javadocs真的说你应该更喜欢使用正则表达式aproach。 How would you do that in a regex based solution? 你会如何在基于正则表达式的解决方案中做到这一点?

Thanks everyone for the answers! 谢谢大家的答案!

Gizmo's answer was definitely out of the box, and a great solution, but unfortunately not appropriate as the format can't be limited to what the Formatter class does in this case. Gizmo的答案绝对是开箱即用的,也是一个很好的解决方案,但遗憾的是不适合,因为格式不能局限于Formatter类在这种情况下的作用。

Adam Paynter really got to the heart of the matter, with the right pattern. Adam Paynter真正了解问题的核心,采用正确的模式。

Peter Nix and Sean Bright had a great workaround to avoid all of the complexities of the regex, but I needed to raise some errors if there were bad tokens, which that didn't do. Peter Nix和Sean Bright有一个很好的解决方法来避免正则表达式的所有复杂性,但是如果有不好的令牌,那么我需要提出一些错误。

But in terms of both doing a regex and a reasonable replace loop, this is the answer I came up with (with a little help from Google and the existing answer, including Sean Bright's comment about how to use group(1) vs group()): 但就完成正则表达式和合理的替换循环而言,这是我提出的答案(谷歌和现有答案的一点帮助,包括Sean Bright关于如何使用group(1)vs group()的评论):

private static Pattern tokenPattern = Pattern.compile("\\{([^}]*)\\}");

public static String process(String template, Map<String, Object> params) {
    StringBuffer sb = new StringBuffer();
    Matcher myMatcher = tokenPattern.matcher(template);
    while (myMatcher.find()) {
        String field = myMatcher.group(1);
        myMatcher.appendReplacement(sb, "");
        sb.append(doParameter(field, params));
   }
    myMatcher.appendTail(sb);
    return sb.toString();
}

Where doParameter gets the value out of the map and converts it to a string and throws an exception if it isn't there. doParameter从地图中获取值并将其转换为字符串,如果不存在则抛出异常。

Note also I changed the pattern to find empty braces (ie {}), as that is an error condition explicitly checked for. 另请注意,我更改了模式以查找空括号(即{}),因为这是显式检查的错误条件。

EDIT: Note that appendReplacement is not agnostic about the content of the string. 编辑: 请注意,appendReplacement与字符串的内容无关。 Per the javadocs, it recognizes $ and backslash as a special character, so I added some escaping to handle that to the sample above. 根据javadoc,它将$和反斜杠识别为一个特殊字符,因此我添加了一些转义来处理上面的示例。 Not done in the most performance conscious way, but in my case it isn't a big enough deal to be worth attempting to micro-optimize the string creations. 没有以最具表现意识的方式完成,但在我的情况下,值得尝试微量优化弦乐创作并不是一件足够大的事情。

Thanks to the comment from Alan M, this can be made even simpler to avoid the special character issues of appendReplacement. 感谢Alan M的评论,可以更简单地避免appendReplacement的特殊字符问题。

好吧,我宁愿使用String.format(),也不想使用更好的MessageFormat

String.replaceAll("{FIRST_NAME}", actualName);

在这里查看javadocs。

Try this: 试试这个:

Note: The author's final solution builds upon this sample and is much more concise. 注意: 作者的最终解决方案建立在此示例的基础上,并且更加简洁。

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();
    }

}

With import java.util.regex.*: 使用import java.util.regex。*:

Pattern p = Pattern.compile("{([^{}]*)}");
Matcher m = p.matcher(line);  // line being "Hello, {FIRST_NAME}..."
while (m.find) {
  String key = m.group(1);
  if (map.containsKey(key)) {
    String value= map.get(key);
    m.replaceFirst(value);
  }
}

So, the regex is recommended because it can easily identify the places that require substitution in the string, as well as extracting the name of the key for substitution. 因此,建议使用正则表达式,因为它可以轻松识别字符串中需要替换的位置,以及提取替换键的名称。 It's much more efficient than breaking the whole string. 它比打破整个字符串更有效率。

You'll probably want to loop with the Matcher line inside and the Pattern line outside, so you can replace all lines. 您可能希望循环使用内部的Matcher线和外部的Pattern线,这样您就可以替换所有线。 The pattern never needs to be recompiled, and it's more efficient to avoid doing so unnecessarily. 该模式永远不需要重新编译,并且避免不必要地这样做更有效。

The most straight forward would seem to be something along the lines of this: 最直接的似乎是这样的:

public static void main(String[] args) {
    String tokenString = "Hello {FIRST_NAME}, this is a personalized message for you.";
    Map<String, String> tokenMap = new HashMap<String, String>();
    tokenMap.put("{FIRST_NAME}", "Jim");
    String transformedString = tokenString;
    for (String token : tokenMap.keySet()) {
        transformedString = transformedString.replace(token, tokenMap.get(token));
    }
    System.out.println("New String: " + transformedString);
}

It loops through all your tokens and replaces every token with what you need, and uses the standard String method for replacement, thus skipping the whole RegEx frustrations. 它遍历所有令牌并用您需要的内容替换每个令牌,并使用标准的String方法进行替换,从而跳过整个RegEx挫折。

Depending on how ridiculously complex your string is, you could try using a more serious string templating language, like Velocity. 根据字符串的复杂程度,您可以尝试使用更严格的字符串模板语言,如Velocity。 In Velocity's case, you'd do something like this: 在Velocity的情况下,你会做这样的事情:

Velocity.init();
VelocityContext context = new VelocityContext();
context.put( "name", "Bob" );
StringWriter output = new StringWriter();
Velocity.evaluate( context, output, "", 
      "Hello, #name, this is a personalized message for you.");
System.out.println(output.toString());

But that is likely overkill if you only want to replace one or two values. 但如果您只想替换一个或两个值,这可能有点过头了。

import java.util.HashMap;

public class ReplaceTest {

  public static void main(String[] args) {
    HashMap<String, String> map = new HashMap<String, String>();

    map.put("FIRST_NAME", "Jim");
    map.put("LAST_NAME",  "Johnson");
    map.put("PHONE",      "410-555-1212");

    String s = "Hello {FIRST_NAME} {LAST_NAME}, this is a personalized message for you.";

    for (String key : map.keySet()) {
      s = s.replaceAll("\\{" + key + "\\}", map.get(key));
    }

    System.out.println(s);
  }

}

The docs mean that you should prefer writing a regex-based tokenizer, IIRC. 文档意味着您应该更喜欢编写基于正则表达式的标记化器IIRC。 What might work better for you is a standard regex search-replace. 什么可能更适合你是一个标准的正则表达式搜索替换。

Generally we'd use MessageFormat in a case like this, coupled with loading the actual message text from a ResourceBundle. 通常我们在这种情况下使用MessageFormat,同时从ResourceBundle加载实际的消息文本。 This gives you the added benefit of being G10N friendly. 这为您提供了G10N友好的额外好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM