文章目录
需求:高效替换字符串中${id}、$(id)这种占位符
官方文档:StringSubstitutor
StrSubstitutor提供了setValueDelimiterMatcher(StrMatcher), setValueDelimiter(char) or setValueDelimiter(String)三种方法,可以自定义默认取值分隔符。
案例
@Test
public void testDataUtil() {
// 替换占位符${}
Map<String, Object> map = new HashMap();
map.put("id", 1001);
map.put("name", "zhupeng");
String str = "/pages/index/home?id=${id}&name=${name}";
String res = replacePlaceholder(str, map);
System.out.println("res = " + res);
// 替换占位符$()
String str2 = "/pages/index/home?id=$(id)&name=$(name)";
StringSubstitutor substitutor = new StringSubstitutor(map, "$(", ")", '$');
String replace = substitutor.replace(str2);
System.out.println("replace = " + replace);
}
/**
* 替换字符串中占位符${}.
*
* @param content 原始字符串
* @param templateParams 要替换的占位符的值
* @return
*/
public String replacePlaceholder(String content, Map<String, Object> templateParams) {
StringSubstitutor sub = new StringSubstitutor(s -> {
if (templateParams.get(s) == null) {
return "";
} else {
return templateParams.get(s).toString();
}
});
return sub.replace(content);
}