Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding parentheses around a string matched by a regex in Python

Tags:

python

regex

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)".

like image 459
snakile Avatar asked Jan 16 '23 16:01

snakile


1 Answers

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)'
like image 150
Tim Pietzcker Avatar answered Jan 18 '23 05:01

Tim Pietzcker