想模版引擎一样,替换字符串中的 ${} 占位符。
那为什么不直接使用模版引擎呢?……
public class A{ private static final String BRACE_LEFT = "{"; private static final String BRACE_RIGHT = "}"; private static final String $ = "$"; /** * 替换字符,占位符限定 ${} * * @param tmp 代码模版 * @param params 参数 * @return PreparedSql */ public static String processMap(@NotNull String tmp, Map<String, ?> params) { StringTokenizer tokenizer = new StringTokenizer(tmp, "${}", true); StringBuilder res = new StringBuilder(tmp.length()); String token; boolean escaped = false; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (escaped) { if ($.equals(token) || BRACE_LEFT.equals(token)) { //占位符中出现美元符或者花括号 throw new IllegalArgumentException("Contain invalid char: " + token); } else if (BRACE_RIGHT.equals(token)) { //标志复位 escaped = false; } else { //参数名占位符 res.append(Converter.toString(params.get(token))); } } else { if ($.equals(token)) { token = tokenizer.nextToken(); if (BRACE_LEFT.equals(token)) { //检索到 '${' 开始尝试获取参数名 escaped = true; } else { //'$'独立出现的场景 res.append($).append(token); } } else { //普通字符 res.append(token); } } } return res.toString(); } }
标签:String,res,equals,占位,token,字符串,BRACE,替换 From: https://www.cnblogs.com/chenss15060100790/p/17466751.html