2017-07-19 159 views
3

在下面的輸入字符串中,我想根據正則表達式搜索條件將「item」替換爲「replaced_item」。替換re.findall()結果中的一部分字符串

re.findall(r"(\bsee\b|\bunder\b|\bin\b|\bof\b|\bwith\b|\bthis\b)(*.{0,4})(item)","i have many roof item in the repeat item of the item inthe item downunder. with any item") 

給輸出:

[('of', ' the ', 'item'), ('with', ' any ', 'item')] 

我想更換 「項」 關鍵字在上面的匹配短語 「replaced_items」。

Expected output: i have many roof item in the repeat item of the replaced_item inthe item downunder. with any replaced_item 
+0

1)使用原始字符串文字來定義正則表達式。另外,'findall'只會返回* captured *子匹配。 2)不清楚你的意思,請發佈失敗的代碼。 –

+0

您需要爲您的正則表達式使用原始字符串文字。即''re.findall(r「(\ bsee \ b ...」)''否則反斜槓將被視爲控制字符 – tzaman

+0

謝謝@WiktorStribiżew。原始字符串文字工作。我編輯了這個問題使其更加清晰。 – Apoorv

回答

1

你可以得到一個\1\2replaced_item替換字符串預期輸出:

import re 
pat = r"\b(see|under|in|of|with|this)\b(*.{0,4})(item)" 
s = "i have many roof item in the repeat item of the item inthe item downunder. with any item" 
res = re.sub(pat, r"\1\2replaced_item", s) 
print(res) 

Python demo

另外,還要注意單詞的邊界現在是如何限制的交替裏面的單詞的上下文(因爲它們被移出,所以在兩端只需要一個字邊界)。

請注意:如果replaced_item是佔位符,並且可以以數字開頭,則應使用r'\1\g<2>replace_item'\g<2>是一個明確的反向引用符號,請參閱python re.sub group: number after \number SO post