我正在嘗試通過正則運算式決議每個元素中包含多個捕獲組的逗號分隔串列。
示范文本
col1 = 'Test String' , col2= 'Next Test String',col3='Last Text String', col4=37
我試過使用這個正則運算式的各種變體
(.*?)\s?=\s?(.*?)\s?,?
但它永遠不會給我我想要的東西,或者如果它接近它就無法處理只有一個元素,反之亦然。
我期待的是一個包含 3 個組的匹配串列
Match1 group 0 the whole match
Match1 group 1 col1
Match1 group 2 'Test String'
Match2 group 0 the whole match
Match2 group 1 col2
Match2 group 2 'Next Test String'
Match3 group 0 the whole match
Match3 group 1 col3
Match3 group 2 'Last Test String'
Match4 group 0 the whole match
Match4 group 1 col4
Match4 group 2 37
(注意我只對第 1 組和第 2 組感興趣)
我故意使這種非語言特定,因為我無法讓它在在線 Regex 除錯器中作業,但是,我的目標語言是 Python 3
提前謝謝你,我希望我已經說清楚了
uj5u.com熱心網友回復:
在(.*?)\s?=\s?(.*?)\s?,?正則運算式得到了只有一個強制性的模式,=。在(.*?)一開始被擴大至最左側=和組捕獲任何文本到最左邊=和之后的可選空白。其余的子模式不必匹配,如果有空格就用 匹配\s?,如果有兩個也匹配,如果有逗號也匹配消耗,.*?部分是簡單跳過,因為它很懶。
如果您想獲得包含單引號的第二個捕獲組,您可以使用
(?:,|^)\s*([^\s=] )\s*=\s*('[^']*'|\S )
請參閱此正則運算式模式。它匹配
(?:,|^)- 匹配 a,或字串開頭的非捕獲組\s*- 零個或多個空格([^\s=] )- 第 1 組:除空格之外的一個或多個字符和=\s*=\s*- 一個=用零個或多個空格包圍的字符('[^']*'|\S )- 第 2 組:'零個或多個非空格'和一個'或一個或多個非空格。
如果要排除單引號,可以對匹配項進行后處理,或在 中使用額外的捕獲組'([^']*)',然后檢查該組是否匹配:
import re
text = "col1 = 'Test String' , col2= 'Next Test String',col3='Last Text String', col4=37"
pattern = r"([^,\s=] )\s*=\s*(?:'([^']*)'|(\S ))"
matches = re.findall(pattern, text)
print( dict([(x, z or y) for x,y,z in matches]) )
# => {'col1': 'Test String', 'col2': 'Next Test String', 'col3': 'Last Text String', 'col4': '37'}
請參閱此 Python 演示。
如果你想用純正則運算式來做到這一點,你可以使用分支重置組:
import regex # pip install regex
text = "col1 = 'Test String' , col2= 'Next Test String',col3='Last Text String', col4=37"
print( dict(regex.findall(r"([^,\s=] )\s*=\s*(?|'([^']*)'|(\S ))", text)) )
請參閱Python 演示(正則運算式演示)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398869.html
上一篇:DIR但選擇檔案名的特定部分
