Adding parentheses around a string matched by regex in Python

Given the regular expression and the string s, I would like to generate a new line in which any substring s corresponding to the regular expression is surrounded by brackets.

For example: My initial line s is "Alan Turing 1912-1954" and my regular expression matches "1912-1954". The newly created line should be "Alan Turing (1912-1954)."

+4
source share
1 answer

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)' 
+9
source

All Articles