Home > Software design >  Regular expressions in Python: Replace starting and closing brackets with dynamic/incremental string
Regular expressions in Python: Replace starting and closing brackets with dynamic/incremental string

Time:10-30

I have a string that holds sub-strings enclosed in starting and closing brackets. For example:

"We want to visit that place (HBD) and meet our friends (DTO) after a long time. We really love having such gatherings at this time of year (XYZ). Let's do it."

I want to replace each pair of starting and closing brackets with a string containing a number that is increasing after every encounter of pair of brackets. Like it should be:

"We want to visit that place sb1-HBD-eb1 and meet our friends sb2-DTO-eb2 after a long time. We really love having such gatherings at this time of year sb3-XYZ-eb3. Let's do it."

If anyone can help me to provide some regular expression way to solve this problem. Thank you.

CodePudding user response:

One approach, it to take advantage of the fact that re.sub can take a function as the repl argument and create a function that will remember how many times it has matched before:

import re
from itertools import count

s = "We want to visit that place (HBD) and meet our friends (DTO) after a long time. We really love having such gatherings at this time of year (XYZ). Let's do it."


def repl(match, counter=count(1)):
    val = next(counter)
    return f"sb{val}-{match.group(1)}-eb{val}"


res = re.sub("\((.*?)\)", repl, s)
print(res)

Output

We want to visit that place sb1-HBD-eb1 and meet our friends sb2-DTO-eb2 after a long time. We really love having such gatherings at this time of year sb3-XYZ-eb3. Let's do it.

The pattern "\((.*?)\)" will match anything inside parenthesis, you can find a better explanation for a similar pattern in the Greedy versus Non-Greedy section of the Regular Expression HOWTO.

  • Related