I am looking for a way to replace a word, however only when its not surounded by quotations.
For example
Replacing Hello with Hi
Hello 'Hello' Nothing → Hi 'Hello' Nothing
Since 'Hello' is in quotes it does not get replaced, but the first Hello does because it is not wrapped with quotes.
Any help would be great!
Regular expressions are awesome:
>>>import re
>>>expression = re.compile("(?!(\"|'))Hello(?!(\"|'))")
>>>expression.sub("Hi",'This string says "Hello" and Hello')
This string says "Hello" and Hi
The only problem with that is that it will also fail to replace "Hello and Hello", if that becomes an issue you can add specific cases for them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With