【问题标题】:Regex Replace Words Containing Specified Substring正则表达式替换包含指定子字符串的单词
【发布时间】: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'

这里的正确方法是什么?

【问题讨论】:

标签: python regex python-regex


【解决方案1】:

这将起作用:

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多