需求
String str = "尊敬的(aaa)的先生女士, 您購買的(bbb)保險"
括號裏面是key, 通過key去拿值,替換
首先把所有的(xxx),截取出來成爲一個集合,
循環集合,拿到每一個(xxx),
去掉().獲取xxx,通過xxx去MAP裏面拿到這個值,把這個值替換掉(xxx)
代碼
public String fillTpl(String tplStr, Map<String, String> data ) {
Matcher m = Pattern.compile("\\{([\\w\\.]*)\\}").matcher(tplStr);
while (m.find()) {
String group = m.group();
group = group.replaceAll("\\{|\\}", "");
String value="";
if(null!=data.get(group)){
value=String.valueOf(data.get(group));
}
tplStr=tplStr.replace(m.group(),value);
}
return tplStr;
}