正则表达式 - 字符串替换"原样"

时间:2014-05-13 21:09:16

标签: python regex

我正在尝试这样做:

单词test应在某些文字中找到,并替换为<strong>test</strong>。但问题是,Test也应该被捕获并替换为<strong>Test</strong>

我试过了:

word = "someword"
text = "Someword and many words with someword"
pattern = re.compile(word, re.IGNORECASE)
result = pattern.sub('<strong>'+word+'</strong>',text)

但在这种情况下,Someword正在变为someword。我使用re错误了吗?

我想要<strong>Someword</strong> and many words with <strong>someword</strong>

1 个答案:

答案 0 :(得分:7)

您需要使用capturing group

>>> import re
>>> word = "someword"
>>> text = "Someword and many words with someword"
>>> pattern = re.compile('(%s)' % word, re.IGNORECASE)
>>> pattern.sub(r'<strong>\1</strong>',text)
'<strong>Someword</strong> and many words with <strong>someword</strong>'

此处\1指的是第一个捕获的组,即括号内捕获的组。

另请参阅python re模块文档的Search and Replace部分。