短信,邮件模板特殊符号${变量名},${1}替换,这一篇就够了

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元

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值