【发布时间】:2023-02-13 16:53:33
【问题描述】:
我需要从 CTAS SQL 语句中获取 select 语句。
例如)
create table table1 as select * from table2
蟒蛇代码:
rgxselect = re.compile(r"(((?:select|with)[\s\S]*))",re.MULTILINE|re.IGNORECASE)
s = rgxselect.search(item)
if s:
selectclause = s.groups()[0]
这适用于第一个例子 但如果像下面的例子那样有括号
create table table1 as (select * from table2)
我想要么得到
(select * from table2)
或者
select * from table2
【问题讨论】:
-
听起来你想试试
\b(?:select|with)\b[^()]* -
谢谢 Wicktor,它适用于简单的选择子句,但如果我有复杂的选择语句,如 select id,case when id in (1,2,3) then ok end as status from table2 它只会捕获到第一个(。最好的解决方案是be capture (select clause) 包括开始和结束括号
-
嵌套括号正则表达式在 Python
re中无法实现。对于 fone 级深层嵌套括号的情况,您可以使用\b(?:select|with)\b[^()]*(?:\([^()]*\)[^()]*)*