1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| private static Pattern templatePattern = Pattern.compile("\\{(\\w+)\\}"); public static String templateEngine(String template, Map<String, Object> params) { StringBuffer sb = new StringBuffer(); Matcher matcher = templatePattern.matcher(template); while(matcher.find()) { String key = matcher.group(1); Object value = params.get(key); matcher.appendReplacement(sb, (value != null) ? Matcher.quoteReplacement(value.toString()) : " "); } matcher.appendTail(sb); return sb.toString(); }
public static void templateDemo() { String template = "Hi {name}, your code is {code}."; Map<String, Object> params = new HashMap<String, Object> (); params.put("name", "老隋"); params.put("code", 24); System.out.println(templateEngine(template, params)); }
|