![](/img/trans.png)
[英]How to "match if there is one occurrence but don't match if the pattern appears multiple times" in regular expression
[英]Regular expression to match repeated occurrence of a pattern
我有一些可能的輸入字符串,如下所示:
Roll|N/A|300x60|(1x1)|AAA|BBB
Desktop|1x1|(1x1)|AAA|BBB
Desktop|NA|(NA)|AAA|BBB
Roll|N/A|N/A|(1x1)|AAA|BBB
從中,我試圖檢測\\d+x\\d+
類型的模式(例如,第一行的'300x60','1x1';第二行的'1x1','1x1';第三行的None
;以及最后一個為“ 1x1”)。 有人可以告訴我如何編寫Python正則表達式搜索以在給定的字符串中不捕獲這種模式的一個或多個或多個出現的情況嗎? 我已經在下面嘗試過,它只捕獲給定句子中模式的第一次出現或第二次出現。 謝謝!
r = re.search('(\(?\d+x\d+\)?)+', my_str)
r.group() # only gives me '320x50' for the first input above
您可以使用
import re
my_strs = ["Roll|N/A|300x60|(1x1)|AAA|BBB", "Desktop|1x1|(1x1)|AAA|BBB", "Desktop|NA|(NA)|AAA|BBB", "Roll|N/A|N/A|(1x1)|AAA|BBB"]
print([re.findall(r'\d+x\d+', s) for s in my_strs])
# => [['300x60', '1x1'], ['1x1', '1x1'], [], ['1x1']]
要點是使用re.findall
將獲取多個匹配項(或捕獲的子字符串,但我建議的模式中沒有捕獲組)。 您遇到的問題是您試圖用1次搜索操作來匹配重復的捕獲 。 由於子字符串不相鄰,不固定,因此只有一個結果。
您可以這樣:
import re
input_strings = ['Roll|N/A|300x60|(1x1)|AAA|BBB', 'Desktop|1x1|(1x1)|AAA|BBB',\
'Desktop|NA|(NA)|AAA|BBB','Roll|N/A|N/A|(1x1)|AAA|BBB']
print [[ j if j else None for j in [re.findall('(\d+x\d+)', i)] ][0] for i in input_strings ]
輸出:
[['300x60', '1x1'], ['1x1', '1x1'], None, ['1x1']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.