5

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

1 Answer 1

10

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)'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.