美文网首页
java 正则 贪婪匹配 匹配sql语句中的引号内容

java 正则 贪婪匹配 匹配sql语句中的引号内容

作者: 姜小嫌 | 来源:发表于2020-01-03 00:04 被阅读0次
    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'
    
    

    相关文章

      网友评论

          本文标题:java 正则 贪婪匹配 匹配sql语句中的引号内容

          本文链接:https://www.haomeiwen.com/subject/yvmaoctx.html