public static void main(String[] args) { String s="尊敬的${name}, 您的订单为:${order} 支付金额为:${pay} 请尽快支付"; System.out.println("替换前:"+s); Map<String,Object> params = new HashMap<>(); params.put("name","Frank"); params.put("order","123456789"); params.put("pay","123"); //使用的时候建议定义为常量或者字段 Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})"); Matcher m = p.matcher(s); StringBuffer sr = new StringBuffer(); while (m.find()) { String group = m.group().replace("$", "").replace("{", "").replace("}", ""); if (params.get(group) == null) { continue; } m.appendReplacement(sr, (String) params.get(group)); } m.appendTail(sr); Matcher m1 = p.matcher(sr.toString()); //可以判断出是否替换成功 if(!m1.find()){ System.out.println("替换后:"+sr.toString()); } }
复制的我代码去跑一下吧