Percy123 Percy123 - 8 months ago 20
Python Question

replacing parts of string using regular expression match in python

In python,
I have to replace every occurance of

(a is b)
[where a,b are non-null strings] in a string s .
I am planning to use
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 :



Use capturing groups and backreferences:

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