正则表达式 - 字符串替换“按原样”

时间:2021-02-14 22:33:00

I am trying to do this:

我想这样做:

word test should be found in some text and be replaced with <strong>test</strong>. but the thing is, Test should be also catched and be replaced with <strong>Test</strong>.

单词测试应在某些文本中找到,并替换为 test 。但问题是,测试也应该被捕获并用测试 替换。

I tried this:

我试过这个:

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

but in this case, Someword is becoming someword. Am I using re somehow wrong?

但在这种情况下,Someword正在变成某个词。我用错了吗?

I want <strong>Someword</strong> and many words with <strong>someword</strong>

我希望 Someword 以及 someword 的许多字词

1 个解决方案

#1


7  

You need to use a 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>'

Here \1 refers to the first captured group, to what was captured inside the parenthesis.

这里\ 1指的是第一个捕获的组,在括号内捕获的内容。

Also see Search and Replace section of the python re module docs.

另请参阅python re模块文档的“搜索和替换”部分。

#1


7  

You need to use a 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>'

Here \1 refers to the first captured group, to what was captured inside the parenthesis.

这里\ 1指的是第一个捕获的组,在括号内捕获的内容。

Also see Search and Replace section of the python re module docs.

另请参阅python re模块文档的“搜索和替换”部分。