Search code examples
pythonregexreplacewords

Python replace whole word including initial special character


I have this piece of code:

import re


variable_to_be_replaced = '$VAR'
value_to_set = 'success'
sample_string = '$VAR VAR $$VAR $VAR1 $VAR1$VAR$VAR2 $VAR'

print re.sub(r'\b' + variable_to_be_replaced + r'\b', value_to_set, sample_string)

I'd like the output to be 'success VAR $success $VAR1 $VAR1success$VAR2 success' and I can only modify the print statement. I know this doesn't work because the variable name starts with $. The delimiters should be the regular word delimiters (minus 1 starting $ symbol).

Any ideas?


Solution

  • You can achieve what you want with this RegEx:

    \$VAR(?=[\s\$]|$)
    

    Which finds '$VAR' when there is a space or a $ after it. More specifically, I use Positive Lookahead to identify parts of the string that are '$VAR ', '$VAR$', or if '$VAR' is the end of the string, and then I replace only the '$VAR' part of that match with the substitution string.

    Check it out here on regex101 with the substitution.

    Output:

    success VAR $success $VAR1 $VAR1success$VAR2 success
    

    Let me know if this helps!