如何从CTAS语句中提取SELECT子句?正则表达式优化需求
从CTAS语句中提取SELECT子句的解决方案
针对普通CTAS语句(如create table table1 as select * from table2),原有正则可正常提取,但带括号的CTAS语句(如create table table1 as (select * from table2))无法适配。以下提供两种正则方案,分别实现提取带括号的完整片段或仅SELECT核心语句:
方案1:提取带括号的完整SELECT片段
如果需要保留外层括号,可使用如下正则:
import re def extract_select_with_brackets(ctas_sql): # 匹配AS后的内容,包含可选的前后括号 rgxselect = re.compile(r"as\s*((?:\()?(?:select|with)[\s\S]*?(?:\))?)$", re.IGNORECASE | re.MULTILINE) match = rgxselect.search(ctas_sql) if match: return match.group(1).strip() return None # 测试示例 test1 = "create table table1 as select * from table2" test2 = "create table table1 as (select * from table2)" print(extract_select_with_brackets(test1)) # 输出: select * from table2 print(extract_select_with_brackets(test2)) # 输出: (select * from table2)
方案2:仅提取SELECT核心语句(去除外层括号)
如果只需要括号内的SELECT内容,可调整正则捕获组:
import re def extract_select_core(ctas_sql): # 匹配AS后的内容,自动忽略外层括号 rgxselect = re.compile(r"as\s*(?:\()?\s*((?:select|with)[\s\S]*?)\s*(?:\))?$", re.IGNORECASE | re.MULTILINE) match = rgxselect.search(ctas_sql) if match: return match.group(1).strip() return None # 测试示例 print(extract_select_core(test1)) # 输出: select * from table2 print(extract_select_core(test2)) # 输出: select * from table2
正则说明
as\s*:匹配CTAS语句中的as关键字及后续任意空白字符(?:\()?:匹配可选的左括号,使用非捕获组避免多余分组(?:select|with):匹配以select或with开头的查询语句(覆盖带CTE的场景)[\s\S]*?:非贪婪匹配任意字符(包括换行),避免匹配到语句意外结尾(?:\))?$:匹配可选的右括号并定位到语句结尾
内容的提问来源于stack exchange,提问作者Krishh
相关产品推荐
相关产品推荐

