在Java中将where子句解析为字符串

时间:2016-02-22 14:35:34

标签: java regex string

我在Java中将以下where子句作为字符串。我想将子选择语句解析成两个字符串。

where create_dtm between (
select start_dtm FROM schema.table 
where table_ID = (SELECT MAX(table_ID) 
FROM schema.table WHERE MAINT_APP = 'JOB01')) 
and (
select end_dtm FROM schema.table
where table_ID = (SELECT MAX(table_ID) 
FROM schema.table WHERE MAINT_APP = 'JOB01')) 

我无法创建正则表达式模式以正确获取这些值,因为区分子选择的结束点有点棘手。

1 个答案:

答案 0 :(得分:1)

试试这个。

String text = "where create_dtm between (select start_dtm FROM schema.table where table_ID = (SELECT MAX(table_ID) FROM schema.table WHERE MAINT_APP = 'JOB01'))"
                + "and (select end_dtm FROM schema.tablewhere table_ID = (SELECT MAX(table_ID) "
                + "FROM schema.table WHERE MAINT_APP = 'JOB01')) ";

        Pattern p = Pattern.compile(
                "where[\\w*\\s*]*\\(\\s*(select[\\w*\\s*\\.*=*\\(\\)\\']*)\\s*and\\s*\\(\\s*(select[\\w*\\s*\\.*=*\\(\\)\\']*)\\s");
        Matcher m = p.matcher(text);
        if (m.matches()) {
            String group1 = m.group(1);
            String group2 = m.group(2);
            System.out.println(group1+"\n"+ group2);
        }

<强>输出

  

选择start_dtm FROM schema.table,其中table_ID =(SELECT   MAX(table_ID)FROM schema.table WHERE MAINT_APP =&#39; JOB01&#39;))选择   end_dtm FROM schema.tablewhere table_ID =(SELECT MAX(table_ID)FROM   schema.table WHERE MAINT_APP =&#39; JOB01&#39;))

注意:它仅适用于您在评论中提到的当前查询