${key}占位符按key值替换所需内容

1,154 阅读1分钟

一、 org.apache.commons.text.StringSubstitutor工具类使用 commons.apache.org/proper/comm…

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

yielding:

  The quick brown fox jumped over the lazy dog.

二、或自己写

public static String renderString(String str, Map map) {
 Set<Entry<String, String>> sets = map.entrySet();
 for (Entry<String, String> entry : sets) {
 String regex = "\\$\\{" + entry.getKey() + "\\}";
 Pattern pattern = Pattern.compile(regex);
 Matcher matcher = pattern.matcher(str);
str = matcher.replaceAll(entry.getValue());
 }
 return str;
}

@Test
public void test2() {
Map map = new HashMap();
map.put("a", "A");
map.put("b", "B");
map.put("c", "C");
String a = "${a}111${b}xx${c}";
System.out.println(renderString(a, map));
}