java解析{{}}变量名以及文本内容替换操作
https://www.jb51.net/article/196303.htm
/** * 根据正则表达式获取文本中的变量名列表 * @param pattern * @param content * @return */ public static List<String> getParams(String pattern, String content) { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(content); List<String> result = new ArrayList<String>(); while (m.find()) { result.add(m.group(1)); } return result; } /** * 根据正则表达式将文本中的变量使用实际的数据替换成无变量的文本 * @param pattern * @param content * @param data * @return */ public static String parse(String pattern, String content, Map<String, String> data) { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(content); StringBuffer sb = new StringBuffer(); while (m.find()) { String key = m.group(1); String value = data.get(key); m.appendReplacement(sb, value == null ? "" : value); } m.appendTail(sb); return sb.toString(); } public static void main(String[] args) { String content = "恭喜{{姓名}}报名成功,请凭报名编号{[code]}到现场参加活动"; String reg = "\\{\\{(.+?)\\}\\}"; List<String> params = getParams(reg, content); System.out.println(params); Map<String, String> data = new HashMap<String, String>(); data.put("姓名", "张三丰"); data.put("code", "930118"); String text = parse(reg, content, data); System.out.println(text); }