pythonregexpython-regex

Regex Replace Words Containing Specified Substring


I am trying to replace words in my string that contain a certain substring. Here is an example

import regex as re

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

I have tried

print(re.sub('cat', 'foo', given_in))
>>>> 'My foo is not like other foos'

and

print(re.sub('.*cat.*', 'foo', given_in))
>>>> 'foo'

What is the right approach here?


Solution

  • This will work:

    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)
    

    output:

    'My foo is not like other foo'