javareplaceAll替换圆括号在⼿写sql的时候,根据参数处理查询条件.
1select * from staff where 1 = 1 and staff_id in ($staffIds)
2 and staff_name in ($staffNames)
⽐如staffId为空,需要把staff_id in ($staffIds) 候设置为true,staffName正常赋值replace替换圆括号
1public static void main(String[] args) {
2 String sqlStr = "select * from staff where 1 = 1 and staff_id in ($staffIds) " +
3 "and staff_name in ($staffNames)";
4 String replaceEmpty = "staff_id in ($staffIds)";
5 String replaceSql = place(replaceEmpty, "true");
6 System.out.println(replaceSql);
7}
结果:
select * from staff where 1 = 1 and true and staff_name in ($staffNames)
直接⽤replace就可以了。
replaceAll替换圆括号
如果是想⽤replaceAll呢?
1public static void main(String[] args) {
2 String sqlStr = "select * from staff where 1 = 1 and staff_id in ($staffIds) " +
3 "and staff_name in ($staffNames)";
4 String replaceEmpty = "staff_id in ($staffIds)";
5 String replaceAllSql = placeAll(Matcher.quoteReplacement(replaceEmpty), "true");
6 System.out.println(replaceAllSql);
7}
结果:
1select * from staff where 1 = 1 and staff_id in ($staffIds)
2and staff_name in ($staffNames)
没有替换成功,为什么呢?
看replaceAll的⽅法:
1public String replaceAll(String regex, String replacement) {
2 return Patternpile(regex).matcher(this).replaceAll(replacement);
3}
regex 对应的是正则的内容,因此要对圆括号进⾏转移下:
String replaceAllSql = replaceEmpty = placeAll("\\(", "[( )]").replaceAll("\\)", "[( )]");
替换前,对圆括号进⾏转义java replace方法
1public static void main(String[] args) {
2 String sqlStr = "select * from staff where 1 = 1 and staff_id in ($staffIds) " +
3 "and staff_name in ($staffNames)";
4 String replaceEmpty = "staff_id in ($staffIds)";
5 replaceEmpty = placeAll("\\(", "[( )]").replaceAll("\\)", "[( )]");
6 String replaceAllSql = placeAll(Matcher.quoteReplacement(replaceEmpty), "true");
7 System.out.println(replaceAllSql);
8}
结果:
select * from staff where 1 = 1 and true and staff_name in ($staffNames)
替换成功。
总结:
字符替换的时候,优先考虑使⽤replace,多个时候,也是⽣效的。如果要使⽤replace的话,使⽤要注意特殊字符的处理。或者⾃⼰写正则进⾏处理。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论