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);

    }

}
原文地址:https://www.cnblogs.com/simpledev/p/5385079.html