NO1.常见的形式:${userName}即${变量名}
这种无非都是使用正则匹配然后根据变量名去替换实现,但是如果不想自己写太多代码去实现的话,可以用apache.commons-text工具的api实现
apache实现
apache.commons
maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
代码实现
String emailTempl="你好,我是${userName},很高兴见到你!";
Map<String,String> replaceMap=new HashMap<String,String>();
replaceMap.put("userName","皮卡丘");
StringSubstitutor sub = new StringSubstitutor(replaceMap);
String sendContent= sub.replace(emailTempl);
system.out.println(sendContent);
// 控制台输出
/***你好,我是皮卡丘,很高兴见到你!*****/
简单高效
模板引擎freemarker实现
maven
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
代码实现
try {
map = new HashMap();
map.put("name", "张三");
map.put("money", 10.155);
map.put("point", 10);
Template template = new Template("strTpl", "您好${name},晚上好!您目前余额:${money?
string(\"#.##\")}元,积分:${point}", new Configuration(new Version("2.3.23")));
StringWriter result = new StringWriter();
// 关键代码
template.process(map, result);
System.out.println(result.toString());
//您好张三,晚上好!您目前余额:10.16元,积分:10
}catch(Exception e){
e.printStackTrace();
}
原生正则表达式实现
代码实现
public static String processTemplate(String template, Map<String, Object> params){
StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
while (m.find()) {
String param = m.group();
Object value = params.get(param.substring(2, param.length() - 1));
m.appendReplacement(sb, value==null ? "" : value.toString());
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args){
Map map = new HashMap();
map.put("name", "李四");
map.put("hour", 3);
map.put("money", 10);
String message = processTemplate("您好{name},晚上好!您目前上网时间还剩:{hour}小时,余额:{money}元", map);
System.out.println(message);
//您好李四,晚上好!您目前上网时间还剩:3小时,余额:10元
}
No2.序号变量名${1},${2}......
JDK API 实现
// MessageFormat.format(pattern, arguments); pattern需要替换的模板,数字0 1 2相当于索引下标 arguments:需要填入模板的数据
String message = MessageFormat.format("您好{0},晚上好!您目前上网时间还剩:{1}小时,余额:{2}元", "李四", 3, 10);
System.out.println(message);
//您好李四,晚上好!您目前上网时间还剩:3小时,余额:10元