gpt4 book ai didi

python - 正则表达式 - 字符串替换 "as is"

转载 作者:太空狗 更新时间:2023-10-30 00:55:53 25 4
gpt4 key购买 nike

我正在尝试这样做:

单词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>

最佳答案

您需要使用 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 指的是第一个捕获的组,即括号内捕获的内容。

另见 Search and Replace python re 模块文档的一部分。

关于python - 正则表达式 - 字符串替换 "as is",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23641623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com