Solution 1:
>>> re.sub(r"\d{4}-\d{4}", r"(\g<0>)", "Alan Turing 1912-1954") 'Alan Turing (1912-1954)'
\g<0> is a link back to the entire match ( \0 does not work, it will be interpreted as \x00 ).
Solution 2:
>>> regex = re.compile(r"\d{4}-\d{4}") >>> regex.sub(lambda m: '({0})'.format(m.group(0)), "Alan Turing 1912-1954") 'Alan Turing (1912-1954)'
source share