Is it possible to use regex to replace a specific character inside a string if it matches a pattern?
For example I want to replace \ with X if it is inside two $ characters, otherwise it should remain unchanged.
$some\string here inside$ and [some here \out side]
and what I expect to have in output is
$someXstring here inside$ and [some here \out side]
re.sub(r'\$*\\*\$', 'X', b) replaces $ with X. How should I do this with one re.sub command?
You can use a lambda with re.sub using str.replace to replace any \\ that matches your pattern
s = "$some\string here inside$ and [some here \out side]"
import re
print(re.sub(r"\$.*\\.*\$",lambda x: x.group().replace("\\","X"),s))
$someXstring here inside$ and [some here \out side]
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