首页 > 解决方案 > 使用 re 模块替换文本时出错

问题描述

我正在尝试替换字符串中的一些文本。我有“微软公司”。我想将其替换为“Microsoft Incorporation”。为此,我尝试过

company = 'Microsoft Inc.'
key = 'Inc.'
pattern = r'\b' + key + r'\b'
# pattern = r'\b' + re.escape(key) + r'\b'
_change = 'Incorporation'
y = re.sub(pattern, _change, company)
print(y)

我没有看到任何替代品。但是当我删除“。” 来自公司和密钥然后它工作正常,但是当有“。” 在字符串中它不会改变任何东西。

标签: pythonregex

解决方案


推荐阅读