日期:2014-05-20 浏览次数:20879 次
public static String composeMessage(String template, Map data) throws Exception { String regex = "\\$|\\{([^}]*)\\}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(template); StringBuffer sb = new StringBuffer(); while(matcher.find()) { String name = matcher.group(1); String value =(String)data.get(name); if(value==null) value=""; else value = value.replaceAll("\\$", "¥");//这句不加的话appendReplacement()这个方法回将$翻译成组 matcher.appendReplacement(sb,value); } matcher.appendTail(sb); return sb.toString(); }
import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Te { public static void main(String args[]) { HashMap<String, String> data = new HashMap<String, String>(); String template = "尊敬的客户${customerName}你好!本次消费金额${amount},您帐户${accountNumber}上的余额为${balance}"; data.put("customerName", "刘明"); data.put("accountNumber", "888888888888888"); data.put("balance", "$1000000000000000000000.00"); data.put("amount", "$5000.00"); try { System.out.println(composeMessage(template, data)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } data = null; template = null; } public static String composeMessage(String template, Map data) throws Exception { String regex = "\\$|\\{([^}]*)\\}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(template); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String name = matcher.group(1); String value = (String) data.get(name); if (value == null) value = ""; else value = value.replaceAll("\\$", "\\\\\\$");// 这句不加的话appendReplacement()这个方法回将$翻译成组 matcher.appendReplacement(sb, value); } matcher.appendTail(sb); return sb.toString(); } }