Given a regex and a string s, I would like to generate a new string in which any substring of s matched by the regex is surrounded by parentheses.
For example: My original string s is "Alan Turing 1912-1954" and my regex happens to match "1912-1954". The newly generated string should be "Alan Turing (1912-1954)".
Solution 1:
>>> re.sub(r"\d{4}-\d{4}", r"(\g<0>)", "Alan Turing 1912-1954")
'Alan Turing (1912-1954)'
\g<0>
is a backreference to the entire match (\0
doesn't work; it would 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)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With