姜小嫌

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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'

posted on 2017-07-07 21:15  姜小嫌  阅读(452)  评论(0编辑  收藏  举报