簡體   English   中英

帶有重復子組的Python正則表達式

[英]Python regular expression with repeating subgroup

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"

我有上面的SQL字符串。 我正在嘗試定義一個正則表達式,該正則表達式將從SQL中獲取所有表(sch.Table1,Table4,sch1.Table2等)。

我使用了以下內容,它僅返回一個table_name ['sch.Table2']

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

在此先感謝您的幫助。

除了使用regex您還可以使用split列表理解:

>>> 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']

或使用regex

>>> [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']]

這是一種簡單的方法:

>>> 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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM