Percy123 Percy123 - 1 year ago 64
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 :


Answer Source

Use capturing groups and backreferences:

re.sub(r"\(([a-z]+)\sis\s([a-z]+)\)", r"(\1,\2)", text)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download