第一种常见的字符串变量替换 占位符替换,如 我叫{0},今年{1}岁;进行替换我们可以使用 MessageFormat.format 类// 替换占位符
MessageFormat.format("我叫{0},今年{1}岁","张三",18);
第二种 模板变量替换,如 我叫{name},今年{age}岁;如果项目中有引入freemaker等模板引擎 可以使用其中相关类进行解析;但是如果项目中没有相关的模板引擎,仅仅为了替换变量引入jar 觉得不值得;我们可以使用正则表达式进行替换/**
* 模板变量替换
*
* @param content
* @param map
* @return
*/
public static String renderString(String content, Map map) {
Set sets = map.entrySet();
for (Map.Entry entry : sets) {
String regex = "\\$\\{" + entry.getKey() + "\\}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
content = matcher.replaceAll(entry.getValue());
}
return content;
}
public static void main(String[] args) throws JsonProcessingException {
String ctx = "验证码为${code},${name}";
Map map = new HashMap<>();
map.put("code", RandomKit.numeric(6));
map.put("sex", "男");
map.put("name", "hoho");
System.out.println(SMSKit.renderString(ctx, map));
}
运行主程序,发现相关变量已经替换为我们想要的值了;结果如下