【问题标题】:regex: find select clause from a CTAS statement正则表达式:从 CTAS 语句中查找选择子句
【发布时间】: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[^()]*(?:\([^()]*\)[^()]*)*

标签: python regex


【解决方案1】:

对于 fone 级深层嵌套括号的情况,您可以使用

(?:select|with)[^()]*(?:([^()]*)[^()]*)*

请参阅regex demo

细节:

  • - 单词边界
  • (?:select|with) - selectwith
  • - 单词边界
  • [^()]* - 除() 之外的零个或多个字符
  • (?:([^()]*)[^()]*)* - 零个或多个序列
    • ([^()]*) - ( + 除了() + ) 之外的零个或多个字符
    • [^()]* - 除() 之外的零个或多个字符

【讨论】:

    猜你喜欢
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 2019-01-24
    • 2013-11-08
    相关资源
    最近更新 更多