例如:
String s = "hello ,{{target}}"
map.put("target","world");
String res = format(s,map);
有什么用呢?
比如在some.properties中配置模板字符串,但是如果用${variable}这种方式,在配置了spring读取properties注入变量的时候,这个变量就找不到会报错。这个时候用一种自定义的字符串模板,可以解决这个问题。
public String format(String template,Map<String,Object> vars){
if(template==null){
throw new RuntimeException("template shold not be null");
}
int preLength = "{{".length();
int sufLength = "}}".length();
Pattern pattern = Pattern.compile("\\{\\{\\s*[a-zA-Z0-9\\._]+\\s*\\}\\}", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(template);
int index = 0;
StringBuilder sb = new StringBuilder();
while(matcher.find(index)){
int start = matcher.start();
String s = matcher.group(0);
String key = s.substring(preLength,s.length()-sufLength).trim();
Object value = vars.get(key);
if(value==null){
throw new RuntimeException("map.get("+key+")结果为null");
}
sb.append(template.substring(index, start)).append(value);
index = matcher.end();
}
sb.append(template.substring(index));
return sb.toString();
}
```