Percy123 Percy123 - 6 months ago 17
Python Question

replacing parts of string using regular expression match in python

In python,
I have to replace every occurance of

(a is b)
with
(a,b)
[where a,b are non-null strings] in a string s .
I am planning to use
re
module .. but I am stuck with how to preserve a,b in the replacement string ..How can I do this?

Ex: "you know that (tiger is animal) and kiwi is bird"
output : "you know that (tiger,animal) and kiwi is bird"


matching regex is :

r"\([a-z]+\sis\s[a-z]+\)"

Answer

Use capturing groups and backreferences:

re.sub(r"\(([a-z]+)\sis\s([a-z]+)\)", r"(\1,\2)", text)