Regex 替换re.findall()结果中字符串的一部分

Regex 替换re.findall()结果中字符串的一部分,regex,python-2.7,Regex,Python 2.7,在下面的输入字符串中,我想根据regex搜索条件将“item”替换为“replaced_item” 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 ', '

在下面的输入字符串中,我想根据regex搜索条件将“item”替换为“replaced_item”

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')]
我想将上述匹配短语中的“item”关键字替换为“replaced_items”


您可以通过替换字符串获得预期的输出:

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)

另外,请注意单词边界现在是如何限制交替中单词的上下文的(因为它们被移出,所以两端只需要一个单词边界)


请注意:如果
replaced\u item
是占位符,并且可以以数字开头,则应使用
r'\1\greplace\u item'
\g
是一种明确的反向引用表示法,请参见。

1)使用原始字符串文本定义正则表达式。另外,
findall
将仅返回捕获的子匹配。2) 不清楚您的意思,请发布失败的代码。您需要为正则表达式使用原始字符串文字。i、 e.
re.findall(r“(\bsee\b…”)
否则反斜杠将被视为控制字符。谢谢@WiktorStribiżew。原始字符串文字有效。我对问题进行了编辑以使其更清晰。好的,因此您需要使用
re.sub
,而不是
re.findall
?或者您想单独运行这两个操作?还是一次完成?:)似乎您只需要一个带有当前模式的
re.sub
和一个
r'\1\2replaced_item'
替换。看,它工作得很好。“\1\2替换项”是我要找的。大多数示例都谈到Perl中的$1$2。非常感谢您的快速帮助。
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)