用于捕获 CTE 的正则表达式

问题描述 投票:0回答:1

我构建了这个正则表达式来捕获雪花 CTE。 CTE 由第一个 WITH 保留关键字定义,但接下来的 CTE 仅需要一个 AS。这是一个例子:

WITH first_rows AS (select top 3 * from table1), other_rows AS (select * from table 2), yet_other_rows AS (select top 2 from another_table)
Select x, y z 
from top_rows inner join other_rows on field1=field2
              inner join yetother_rows on field1=field2

然后,带有 CTE 的 with 子句可以出现在 SQL 中的任何位置,因为它也可以在子查询中使用。

我编写的正则表达式捕获了几个 CTE 名称,仅忽略了其余的大部分名称。这个正则表达式有什么问题

(?:.*?)with\s+(\w+)\s+as.*?(?:\,\s+(\w+)\s+as\s+.*)

谢谢

python regex common-table-expression
1个回答
0
投票

一般来说,这是一个合适的 SQL 解析器的任务。话虽如此,如果我们假设 only CTE 定义以单词名称开头,后跟

AS
、空格和
(
,那么我们可以尝试以下方法:

import re

inp = """WITH first_rows AS (select top 3 * from table1), other_rows AS (select * from table 2), yet_other_rows AS (select top 2 from another_table)
Select x, y z 
from top_rows inner join other_rows on field1=field2
              inner join yetother_rows on field1=field2"""

names = re.findall(r'(\w+) AS \(', inp)
print(names)  # ['first_rows', 'other_rows', 'yet_other_rows']
© www.soinside.com 2019 - 2024. All rights reserved.