带重复子组的Python正则表达式

带重复子组的Python正则表达式,python,regex,Python,Regex,我有如上所示的SQL字符串。我试图定义一个正则表达式,它将从SQLs获取所有表(sch.Table1、Table4、sch1.Table2等) 我使用了以下内容,它只返回一个表名['sch.Table2'] s2="SELECT a,b,c FROM sch.Table1 a, Table4, (SELECT a, b, c FROM (select c,d FROM sch1.Table2 where x=1),Table3 where ....)" s3="SELECT a,b,d,e FR

我有如上所示的SQL字符串。我试图定义一个正则表达式,它将从SQLs获取所有表(sch.Table1、Table4、sch1.Table2等)

我使用了以下内容,它只返回一个表名
['sch.Table2']

s2="SELECT a,b,c FROM sch.Table1 a, Table4, (SELECT a, b, c FROM (select c,d FROM sch1.Table2 where x=1),Table3 where ....)"
s3="SELECT a,b,d,e FROM sch.Table1 a, sch.Table4 b, schb.Table3 WHERE 1=1"
s4="SELECT a,b,c FROM sch.table1 a,sch.table2 b WHERE colb=colc and col2=(SELECT colid FROM SCH2.TABLE3,SCH3.TABLE4 WHERE 1=1"

提前感谢您的帮助。

您可以在列表理解中使用
split
而不是
regex

w1 = re.findall(r"(?:SELECT\s+.+\s+FROM\s)(?:(\w*\.*\w+)\s*\w?,?)",s2,re.IGNORECASE)
print w1
或使用
regex

>>> l=[s2,s3,s4]
>>> [i for s in l for i in s.split() if 'table' in i or 'Table' in i]
['sch.Table1', 'Table4,', 'sch1.Table2', 'x=1),Table3', 'sch.Table1', 'sch.Table4', 'schb.Table3', 'sch.table1', 'a,sch.table2']

这里有一个简单的方法:

>>> [re.findall(r'[\w\.]+Table\d|table\d',s) for s in l]
[['sch.Table1', 'sch1.Table2'], ['sch.Table1', 'sch.Table4', 'schb.Table3'], ['table1', 'table2']]

使用sql解析器。regex对你毫无用处。用你的代码对我有用。我得到了
['sch1.Table2']
['sch.Table1']
['SCH2.TABLE3']
。感谢Simonzack建议使用sqlparser。我在下面的URL中使用了脚本,并对其进行了一些小的调整,以获得表名。感谢亚当、卡斯拉和巴特的帮助。
>>> s2="SELECT a,b,c FROM sch.Table1 a, Table4, (SELECT a, b, c FROM (select c,d FROM sch1.Table2 where x=1),Table3 where ....)"
>>> s3="SELECT a,b,d,e FROM sch.Table1 a, sch.Table4 b, schb.Table3 WHERE 1=1"
>>> s4="SELECT a,b,c FROM sch.table1 a,sch.table2 b WHERE colb=colc and col2=(SELECT colid FROM SCH2.TABLE3,SCH3.TABLE4 WHERE 1=1"
>>> re.findall(r"[\w\.]*Table.?",s2,re.IGNORECASE)
['sch.Table1', 'Table4', 'sch1.Table2', 'Table3']
>>> re.findall(r"[\w\.]*Table.?",s3,re.IGNORECASE)
['sch.Table1', 'sch.Table4', 'schb.Table3']
>>> re.findall(r"[\w\.]*Table.?",s4,re.IGNORECASE)
['sch.table1', 'sch.table2', 'SCH2.TABLE3', 'SCH3.TABLE4']