zoukankan      html  css  js  c++  java
  • java正则表达式解析短信模板

    /**
     * 
     */
    package testJava.java;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * @author xxx.sjtu
     * @function
     * @date 2016年4月12日
     * @version
     */
    public class ReplaceTest {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            String tempalteContent = "您的“$CarBrand$”(车牌$CarPlateNum$)已经完成租用(订单号:$orderNo$)。本次租金收益$RentIncome$元,$ServiceExpense$$ServiceExpenseProxy$$You2RenterAdjust$$Renter2YouAdjust$$HardwareDeposit$$ownerTransDebt$$TotalIncome$在1个工作日后结算至您设置的银行卡中。您可在App车主收益页面查看详情";
            Map contentParamMap = new HashMap();
            contentParamMap.put("CarBrand", "奥迪");
            contentParamMap.put("CarPlateNum", "沪A0001");
            contentParamMap.put("orderNo", "1245221158");
            contentParamMap.put("RentIncome", "2000");
            contentParamMap.put("ServiceExpense", "平台服务费100元,");
            
            Scanner sc = new Scanner(tempalteContent);
            StringBuffer buf = new StringBuffer();
            try{
                Pattern p = Pattern.compile("[$]([^$]*?)[$]");
                while (sc.hasNext()) {
                    System.out.println(sc.toString());
                    Matcher m = p.matcher(sc.nextLine());
                    while (m.find()) { //查找并替换参数
                        System.out.println(m.group(1));
                        //从map中根据key获取值
                        m.appendReplacement(buf, contentParamMap.get(m.group(1)) != null ? contentParamMap.get(m.group(1)).toString() : "");
                    }
                    m.appendTail(buf);
                }
    //            if(StringUtils.isEmpty(buf.toString())){
    //                buf.append(tempalteContent);
    //            }
            }catch(Exception e){
    //            logger.error("替换短信模板内容报错!",e);
                e.printStackTrace();
            }finally{
                sc.close();
            }
            System.out.println("buf=" + buf);
    
        }
    
    }
  • 相关阅读:
    【t090】吉祥数
    【u221】分数
    【u212】&&【t036】最大和
    【u125】最大子树和
    【u124】环状最大两段子段和
    【u123】最大子段和
    【u122】迎接仪式
    【u121】教主的花园
    【u118】日志分析
    【u117】队列安排
  • 原文地址:https://www.cnblogs.com/simpledev/p/5385079.html
Copyright © 2011-2022 走看看