${var}变量替换

${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); }

 

posted on 2016-03-07 12:52  石头hah  阅读(878)  评论(0编辑  收藏  举报

导航