短信,邮件模板特殊符号${变量名},${1}替换,根本不需要啥算法

    技术2022-07-12  106

    1.首先我们来看比较常见的形式:${userName}即${变量名}

     这种无非都是使用正则匹配然后根据变量名去替换实现,但是如果不想自己写太多代码去实现的话,可以用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(); }

    2.序号变量名${1},${2}......

    使用内置String.format

    String message = MessageFormat.format("您好{0},晚上好!您目前上网时间还剩:{1}小时,余额:{2}元", "李四", 3, 10); System.out.println(message); //您好李四,晚上好!您目前上网时间还剩:3小时,余额:10元

    3.原生正则表达式

    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元 }

     

    Processed: 0.019, SQL: 9