Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a specific character if it is inside a string that matches a pattern in Python

Tags:

python

regex

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?

like image 424
Esildor Avatar asked Dec 01 '25 06:12

Esildor


1 Answers

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]
like image 95
Padraic Cunningham Avatar answered Dec 02 '25 19:12

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!