Replacing unquoted words only in Python

后端 未结 6 942
情深已故
情深已故 2021-01-21 04:03

I am looking for a way to replace a word, however only when its not surounded by quotations.

For example Replacing Hello with Hi

6条回答
  •  野性不改
    2021-01-21 04:29

    Try this:

    import re
    
    def callback(match):
       rep = 'Hi'
       return match.group(1)+rep+match.group(2)
    
    your_string = "Hello 'Hello' Nothing"
    print re.sub("([^\']|^)Hello([^\']|$)", callback, your_string)
    

    This will match the word Hello that is surrounded by anything except ' (^ in [] means anything but). I also added the |^ and |$ to match the word Hello that is in the end or the beginning of the string.

    It will replace it by the first part in parenthesis along with Hi and the second part (whatever they are).

提交回复
热议问题