pattern replace with specific exception
-
I am looking for a substution RegEx which prefixes all words with a caret, except when followed by a bracket. E.g. "func(x)=y" must be replaced by "func(^x)=^y" . I came up with (in Python code): re.sub(r'([A-Za-z][A-Za-z0-9_]*)([^(]|$)', r'^\1\2', 'func(x)=y') but that does not work. "f(x)=y" is replaced correctly, but it fails when the word before the bracket has more characters. I suspect it can be done with a single substitution, but I can't figure it out. I guess my solution does not work because the first bracketed regular expression is not greedy enough. What am I doing wrong?
-
I am looking for a substution RegEx which prefixes all words with a caret, except when followed by a bracket. E.g. "func(x)=y" must be replaced by "func(^x)=^y" . I came up with (in Python code): re.sub(r'([A-Za-z][A-Za-z0-9_]*)([^(]|$)', r'^\1\2', 'func(x)=y') but that does not work. "f(x)=y" is replaced correctly, but it fails when the word before the bracket has more characters. I suspect it can be done with a single substitution, but I can't figure it out. I guess my solution does not work because the first bracketed regular expression is not greedy enough. What am I doing wrong?
I asked ChatGPT :-\ and it suggested \b for word boundaries and (?!.) for negative look ahead assertion, so: re.sub(r'(\b[A-Za-z][A-Za-z0-9_]*\b)(?!\()', r'^\1', 'val1+function(x)=y+val2+f(xx)') '^val1+function(^x)=^y+^val2+f(^xx)' works.....
-
I am looking for a substution RegEx which prefixes all words with a caret, except when followed by a bracket. E.g. "func(x)=y" must be replaced by "func(^x)=^y" . I came up with (in Python code): re.sub(r'([A-Za-z][A-Za-z0-9_]*)([^(]|$)', r'^\1\2', 'func(x)=y') but that does not work. "f(x)=y" is replaced correctly, but it fails when the word before the bracket has more characters. I suspect it can be done with a single substitution, but I can't figure it out. I guess my solution does not work because the first bracketed regular expression is not greedy enough. What am I doing wrong?