mvel 配合正则表达式实现文本替换
mvel 依赖
<dependency> <groupId>org.mvel</groupId> <artifactId>mvel2</artifactId> <version>2.0</version> </dependency>
使用
public static String processTemplate(String template, Map<String, Object> params){ StringBuffer sb = new StringBuffer(); Matcher m = Pattern.compile("\\$\\{[\\w,\\.]+\\}").matcher(template); while (m.find()) { String param = m.group(); Object value = MVEL.eval(param.substring(2, param.length() - 1), params); m.appendReplacement(sb, value==null ? "" : value.toString()); } m.appendTail(sb); return sb.toString(); } public static void main(String[] args) { Map<String, Object> salesMap = new HashMap<>(); salesMap.put("name", "ttttttttttttt"); Map<String, Object> param = new HashMap<>(); param.put("aaaaa",999999999); param.put("bbb",10000000000L); param.put("sales", salesMap); Map<String, Object> param2= new HashMap<>(); param2.put("param", param); String s = StringUtil.processTemplate("sfdfdsfsdfsd${param.sales.name}dfsfsd", param2); System.out.println(s); }