如何最好地参数化字符串

时间:2018-09-17 06:55:13

标签: java string replace parameterization

例如,我有:

String templateString = "Hi {{customerName}}, you have successfully ordered a {{itemName}}."
Map<String, String> parameters = new HashMap<>();
parameters.put("customerName", "Bob");
parameters.put("itemName", "sofa");

所需的输出: "Hi Bob, you have successfully ordered a sofa."

获得所需输出的最佳方法(安全,可维护,省时等)是什么?

我想到了做一些简单的事情:

String output = templateString;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
    output = output.replace("{{" + entry.getKey() + "}}", entry.getValue());
}

有更好的方法吗?

4 个答案:

答案 0 :(得分:1)

取决于所需的模板系统的复杂程度。已经有很多了。

两个例子是:

答案 1 :(得分:0)

另一种方法是使用Mustache.javadocs

String templateString = "Hi {{customerName}}, you have successfully ordered a {{itemName}}.";
Map<String, String> parameters = new HashMap<>();
parameters.put("customerName", "Bob");
parameters.put("itemName", "sofa");

Writer writer = new StringWriter();
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(new StringReader(templateString), "example");
mustache.execute(writer, parameters);
writer.flush();
System.out.println(writer.toString());

答案 2 :(得分:0)

使用Map中的键来获取值会更好

            String output = templateString;
            output = output.replace("{{customerName}}",parameters.get("customerName"));
            output = output.replace("{{itemName}}",parameters.get("itemName"));

答案 3 :(得分:0)

除了其他答案中已经提供的解决方案之外,您还可以使用 Apache Commons Text 中的StringSubstitutor

来自https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html的示例:-

 Map valuesMap = HashMap();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumps over the ${target}.";
 StringSubstitutor sub = new StringSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);