簡體   English   中英

如何匹配括號外的特定單詞並忽略括號中的單詞?

[英]how to match a specific word outside of parentheses and ignore the word in parentheses?

我正在使用 python 正則表達式來處理如下文本字符串:

select t2.f1 as rf1, (select t1.f1 from table1 t1  where t1.f1 = t2.f2) as rff, t2.f3 as rf3 FROM table2 t2

上面的字符串中有兩個“from”。 一個在括號內,另一個在括號外。 我想在第二個“來自”之前獲得匹配的文本:

select t2.f1 as rf1, (select t1.f1 from table1 t1  where t1.f1 = t2.f2) as rff, t2.f3 as rf3 

我的測試 python 正則表達式是:

^\s*select\s+(?P<SELECTED>.+?)\s+from

返回: SELECTED t2.f1 as rf1, (select t1.f1

任何人都知道如何修改正則表達式以獲得SELECTED t2.f1 as rf1, (select t1.f1 from table1 t1 where t1.f1 = t2.f2) as rff, t2.f3 as rf3

非常感謝你的幫助。

你可以用這個

^\s*select\s+(?P<SELECTED>.+?)\s+(from).*?(?=FROM)

你可以在這里嘗試它找到完整的匹配在線正則表達式

如果你知道你總是 2 select 和

你可以用這個

^\s*select.*(from).*?(?=FROM)

你可以看到選項2

這是我在 python3.7 中的解決方案:

 pat1     = "^\s*select\s+(?P<SELECTED>.*(from)*)\s+(?=from)"
 selected = re.compile(pat1, ((re.IGNORECASE | re.DOTALL) | re.MULTILINE))

 txt = "select t2.f1 as rf1, (select t1.f1 from table1 t1  where t1.f1 = t2.f2) as rff, t2.f3 as rf3 FROM table2 t2"
 selected.match(txt)

感謝@Beny Gj 的幫助。

暫無
暫無

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

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