我以下面的句子為例
isaac morka morka morka
我試圖得到以下結果:
isaac morka
我嘗試了以下代碼:
re.findall(r'isaac[\s\w] (?=morka)', 'isaac morka morka morka')
但得到的結果不正確
['isaac morka morka']
uj5u.com熱心網友回復:
isaac[\s\S] ?morka您可以在不使用環視的情況下簡化您的正則運算式。
在此處測驗正則運算式:https ://regex101.com/r/bmp5pH/1
uj5u.com熱心網友回復:
您可以使用
rgx = r'\bisaac\b|\bmorka\b(?!.*\bmorka\b)'
str = 'isaac morka morka morka'
re.findall(rgx, str)
#=> ["isaac", "morka"]
Python 演示<- \(ツ)/ ->正則運算式演示
讓我們分解正則運算式。
\bisaac\b # match 'isaac' with word boundaries fore and aft
| # or
\bmorka\b # match 'morca' with word boundaries fore and aft
(?! # begin negative lookahead
.* # match zero or more characters
\bmorka\b # match 'morca' with word boundaries fore and aft
) # end negative lookahead
如果要回傳一個唯一單詞串列,使得串列中的每個單詞在字串中至少出現一次,則可以撰寫以下內容。
str = "isaac morka louie morka isaac morka"
rgx = r'\b(\w )\b(?!.*\b\1\b)'
re.findall(rgx, str)
#=> ['louie', 'isaac', 'morka']
演示
\b(\w )\b # match one or more word characters with word boundaries
# fore and aft and save to capture group 1
(?! # begin negative lookahead
.* # match zero or more characters
\b\1\b # match the content of capture group 1 with word boundaries
# fore and aft
) # end negative lookahead
uj5u.com熱心網友回復:
正則運算式與@anotherGatsby 使用的相同。下面的代碼片段給出了您需要的結果。
x=['isaac morka morka']
str = str(x)
rex =re.compile('isaac[\s\S] ?morka')
列印(re.findall(雷克斯,str))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432559.html
