${age},${name} 给定一个上下文 Map<String,String> context 使用上下文替换变量private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{[^\\}\\$\u0020]+\\}"); private static final int MAX_SUBST = 20; private static String substituteVars(String expr,Map<String,String> paramMap) { if (expr == null) { return null; } Matcher match = VAR_PATTERN.matcher(""); String eval = expr; for(int s=0; s<MAX_SUBST; s++) { match.reset(eval); if (!match.find()) { return eval; } String var = match.group(); var = var.substring(2, var.length()-1); // remove ${ .. } String val = null; try { val = paramMap.get(var); } catch(SecurityException se) { } /*if (val == null) { val = "aa"; }*/ if (val == null) { return eval; // return literal ${var}: var is unbound } // substitute eval = eval.substring(0, match.start())+val+eval.substring(match.end()); } throw new IllegalStateException("Variable substitution depth too large: " + MAX_SUBST + " " + expr); }
时间: 2024-12-29 12:04:37