Given the following string:
"-local locally local test local."
my objective is to replace the string “local” with “we” such that the result becomes
"-local locally we test local."
so far (with the help from the guys here at stackoverflow: Python: find exact match) I have been able to come up with the following regular expression:
variable='local'
re.sub(r'\b%s([\b\s])' %variable, r'we\1', "-local locally local test local.")
However I have two problems with this code:
-
The search goes through the minus sign and the output becomes:
'-we locally we test local.'where it should have been
'-local locally we test local.' -
searching for a string starting with a minus sign such as “-local” fails the search
Try the following:
The regex that was suggested in the other question is kind of odd, since
\bin a character class means a backspace character.Basically what you have now is a regex that searches for your target string with a word boundary at the beginning (going from a word character to a non-word character or vice versa), and a whitespace character at the end.
Since you don’t want to match the final “local” since it is followed by a period, I don’t think that word boundaries are the way to go here, instead you should look for whitespace or beginning/end of string, which is what the above regex does.
I also used
re.escapeon the variable, that way if you include a characters in your target string like.or$that usually have special meanings, they will be escaped and interpreted as literal characters.Examples: