1

对不起,如果问题是混乱的。从下面的文字

value = ( select max( tbl.column_name ) from table tbl where trim(colum2)='value1'
and (trim((colum3)))='value3')

我想要下面的输出

select max( tbl.column_name ) from table tbl where trim(colum2)='value1'
    and (trim((colum3)))='value3'

基本上从 select max( until ) except ) 开始匹配左括号。

(select[ ]*max[ ]*\(.*column_name[ ]*\)[^)]*)

这只匹配到 trim(colum2 Need help to escape bracket ) 是否有一个左括号,包括任何嵌套

谢谢

编辑:我终于做到了java,如下所示。但想知道REGEX解决方案

String sql = readFile(file.getPath());
Pattern patTabs = Pattern.compile("(\\([ \n]*SELECT[ \n]*MAX[ \n]*\\(.*COLUMN_NAME[ \n]*\\))", Pattern.CASE_INSENSITIVE);
Matcher tabMat = patTabs.matcher(sql);
while (tabMat.find()) {
    int i = tabMat.start();
    int j = tabMat.end();
    int l = 0;
    for (j = tabMat.end(); j < sql.length(); j++) {
        char k = sql.charAt(j);
        if (k == '(') {
            l++;
        }
        if (k == ')') {
            if (l == 0) {
                break;
            } else {
                l--;
            }
        }
    }
    System.out.println(sql.substring(i, j + 1))
}
4

1 回答 1

0

如果您想要一个优雅的解决方案,您必须在这些表达式中用空格替换行终止符。所以你需要改变这个-

value = ( select max( tbl.column_name ) from table tbl where trim(colum2)='value1'
and (trim((colum3)))='value3')

对此——

value = ( select max( tbl.column_name ) from table tbl where trim(colum2)='value1' and (trim((colum3)))='value3')

编辑:之后,您可以使用\( *?(select *?max\( .*?column_name *?\).+) *?\)来匹配您期望的表达式。

这是一个现场演示

如果您真的不想替换表达式中的行终止符,而是想使用

value = ( select max( tbl.column_name ) from table tbl where trim(colum2)='value1'
and (trim((colum3)))='value3')

可以用这个\([ \n]*?(select[ \n]*?max\([ \n].*?column_name[ \n]\)[\D\d \n]+)[ \n]*?\)。但我强烈建议不要这样做,因为如果您将多个value = ( select..... )输入到相同的模式中,它将无法正常工作。

这是一个现场演示

于 2020-02-27T09:18:26.310 回答