public class TemplateReplaceTest {
public static void main(String[] args) {
String sql = "INSERT INTO ${tableName} " +
"(${COLUMNS}) " +
"VALUES (${VALUES})";
Map<String,String> map = new HashMap<>();
map.put("tableName","product");
map.put("COLUMNS","id,age,name");
map.put("VALUES","000001,20,'xiaoming'");
System.out.println(attributesReplace(sql,map));
}
/**
* 变量替换
* @param sql
* @param map
* @return
*/
public static String attributesReplace(String sql, Map<String,String> map){
//生成匹配模式的正则表达式
String patternString = "\\$\\{(" + StringUtils.join(map.keySet(), "|") + ")\\}";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(sql);
//两个方法:appendReplacement, appendTail
StringBuffer stringBuffer = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(stringBuffer, map.get(matcher.group(1)));
}
matcher.appendTail(stringBuffer);
return stringBuffer.toString();
}
}
执行结果:
INSERT INTO product (id,age,name) VALUES (000001,20,'xiaoming')
StringUtils依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.11</version> </dependency>
标签:map,String,正则表达式,matcher,stringBuffer,VALUES,sql,替换,模板 From: https://www.cnblogs.com/yangh2016/p/16745594.html