【发布时间】:2021-05-26 17:49:52
【问题描述】:
我正在尝试替换字符串中包含某个子字符串的单词。这是一个例子
import regex as re
given_in = 'My cat is not like other cats'
desired_out = 'My foo is not like other foo'
我试过了
print(re.sub('cat', 'foo', given_in))
>>>> 'My foo is not like other foos'
和
print(re.sub('.*cat.*', 'foo', given_in))
>>>> 'foo'
这里的正确方法是什么?
【问题讨论】:
-
在这么简单的示例中,也许只需使用
\w*cat\w*? -
re.sub(r'\w*cat\w*', 'foo', in)或re.sub(r'\bcat\w*', 'foo', in),见How to find words containing a certain letter with Regular Expressions?
标签: python regex python-regex