我正在尝试这样做:
单词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>
答案 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部分。