標籤:
/** * */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); }}
javaRegex解析簡訊模板