I’m trying to write a regex to replace strings if not surrounded by single quotes.
For example I want to replace FOO with XXX in the following string:
string = "' FOO ' abc 123 ' def FOO ghi 345 ' FOO '' FOO ' lmno 678 FOO '"
the desired output is:
output = "' FOO ' abc 123 ' def FOO ghi 345 ' XXX '' XXX ' lmno 678 FOO '"
My current regex is:
myregex = re.compile("(?<!')+( FOO )(?!')+", re.IGNORECASE)
I think I have to use look-around operators, but I don’t understand how… regex are too complicated to me 😀
Can you help me?
Here’s how it could be done:
[EDIT]
The
re.subfunction will accept as a replacement either a string template or a function. If the replacement is a function, every time it finds a match it’ll call the function, passing the match object, and then use the returned value (which must be a string) as the replacement string.As for the pattern itself, as it searches, if there’s a
'at the current position it’ll match up to and including the next', otherwise it’ll match up to but excluding the next'or the end of the string.The replacement function will be called on each match and return the appropriate result.
Actually, now I think about it, I don’t need to use a group at all. I could do this instead: