这种无非都是使用正则匹配然后根据变量名去替换实现,但是如果不想自己写太多代码去实现的话,可以用apache.commons-text工具的api实现
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(); }使用内置String.format
String message = MessageFormat.format("您好{0},晚上好!您目前上网时间还剩:{1}小时,余额:{2}元", "李四", 3, 10); System.out.println(message); //您好李四,晚上好!您目前上网时间还剩:3小时,余额:10元