正则表达式替换包含指定子字符串的单词

Regex Replace Words Containing Specified Substring

我正在尝试替换字符串中包含特定子字符串的单词。这是一个例子

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'

这里正确的方法是什么?

这会起作用:

import re

given_in = 'My cat is not like other cat'
desired_out = 'My foo is not like other foo'

out = re.subn("\w*(cat)\w*", "foo", given_in)
print(out)

输出:

'My foo is not like other foo'