那麼首先你需要修復你的正則表達式來捕捉整個集團解釋爲字符:
>>> s = '[[merit|merited]] and [[eat|eaten]] and [[go]]'
>>> p = '(\[\[(?:[a-zA-Z]*\|)*([a-zA-Z]*)\]\])'
>>> [('[[merit|merited]]', 'merited'), ('[[eat|eaten]]', 'eaten'), ('[[go]]', 'go')]
[('[[merit|merited]]', 'merited'), ('[[eat|eaten]]', 'eaten'), ('[[go]]', 'go')]
這符合整個[[whateverisinhere]]
並分離了全場比賽爲1組,只是一錘定音爲組2.您可以使用比令牌\2
只有2組更換整個比賽:
>>> re.sub(p,r'\2',s)
'merited and eaten and go'
或更改模式:
p = '\[\[(?:[a-zA-Z]*\|)*([a-zA-Z]*)\]\]'
其擺脫分組整場比賽,你想要什麼1組,只有組。你可以這樣做:
>>> re.sub(p,r'\1',s)
具有相同的效果。
POST編輯:
我忘了提,我居然改變了你的正則表達式所以這裏的解釋是:
\[\[(?:[a-zA-Z]*\|)*([a-zA-Z]*)\]\]
\[\[ \]\] #literal matches of brackets
(?: )* #non-capturing group that can match 0 or more of whats inside
[a-zA-Z]*\| #matches any word that is followed by a '|' character
(... ) #captures into group one the final word
我覺得這是比你原來有什麼強大,因爲它也將發生變化如果有超過2個選項:
>>> s = '[[merit|merited]] and [[ate|eat|eaten]] and [[go]]'
>>> p = '\[\[(?:[a-zA-Z]*\|)*([a-zA-Z]*)\]\]'
>>> re.sub(p,r'\1',s)
'merited and eaten and go'
我不明白這個問題嗎?看起來正則表達式已經在做你想做的事情了?除非你想're.findall(p,s)[ - 1]'? – zwol
對不起,不清楚。編輯了這個問題。 – zadrozny
通過你的話只需在列表中循環,並保持通話re.findall – Illusionist