Python Regex instantly replace groups

user1467267 picture user1467267 · Dec 23, 2012 · Viewed 81k times · Source

Is there any way to directly replace all groups using regex syntax?

The normal way:

re.match(r"(?:aaa)(_bbb)", string1).group(1)

But I want to achieve something like this:

re.match(r"(\d.*?)\s(\d.*?)", "(CALL_GROUP_1) (CALL_GROUP_2)")

I want to build the new string instantaneously from the groups the Regex just captured.

Answer

Martin Ender picture Martin Ender · Dec 23, 2012

Have a look at re.sub:

result = re.sub(r"(\d.*?)\s(\d.*?)", r"\1 \2", string1)

This is Python's regex substitution (replace) function. The replacement string can be filled with so-called backreferences (backslash, group number) which are replaced with what was matched by the groups. Groups are counted the same as by the group(...) function, i.e. starting from 1, from left to right, by opening parentheses.