public class Demo {
public static void main(String[] args) {
String sql1 = "use test;select * from default.abc where dt='abc;faf;fff' and ct=\"2012;43\" ; ";
sql1 = "select * from aaa where dt= '20 ;12; 34;3' AND name='fafae; fa ; a'";
//配置“” 或 ‘’ 里的内容
Pattern p1 = Pattern.compile("'.*'|\".*\"");//贪婪匹配
Matcher m1 = p1.matcher(sql1);
String replace1 = null;
while (m1.find()) {
// 贪婪匹配 group= '20 ;12; 34;3' AND name='fafae; fa ; a'
String group = m1.group();
if (group.contains(";")) {
replace1 = sql1.replace(group, "'PLACEHOLDER'");
sql1 = replace1;
}
}
System.out.println("贪婪匹配" + sql1);
String sql2 = "select * from aaa where dt= '20 ;12; 34;3' AND name='fafae; fa ; a'";
//配置“” 或 ‘’ 里的内容
Pattern p2 = Pattern.compile("'.*?'|\".*?\"");//非贪婪匹配
Matcher m2 = p2.matcher(sql2);
String replace2 = null;
while (m2.find()) {
// 第一次匹配 group '20 ;12; 34;3'
// 第二次匹配 group 'fafae; fa ; a'
String group = m2.group();
if (group.contains(";")) {
replace2 = sql2.replace(group, "'PLACEHOLDER'");
sql2 = replace2;
}
}
System.out.println("非贪婪匹配" + sql2);
}
}
结果:
贪婪匹配 select * from aaa where dt= 'PLACEHOLDER'
非贪婪匹配select * from aaa where dt= 'PLACEHOLDER' AND name='PLACEHOLDER'