Victor Martins
Victor Martins

Reputation: 769

Recursion with re.sub()

If we use it as follows:

re.sub("a\(\s*\d*\s*,\s*\d*\s*\)", "100", "a(440, 330)"

we get:

>> "100"

Now, for example we have a() inside of a():

re.sub("a\(\s*\d*\s*,\s*\d*\s*\)", "100", "a(30, a(30,30))")

we get:

>> 'a(30, 100)'

But I want something like this:

1. a(30, a(30,30)) # replace the nested 'a' 
2. a(30, 100) # now work with the remainder
3. '100' # final string

Sorry for my english.

Upvotes: 2

Views: 2521

Answers (2)

Shank_Transformer
Shank_Transformer

Reputation: 155

You can do it without the while loop using '+' option which stand for multiple match.

re.sub("[a\(\s*\d*\s*,\s*\d*\s*\)]+", "100", "a(30, a(30,30))")

I too tend to forget the regex option which some time does not strike you right away. Make a list/print & keep it front of you. Invariably you will end up noticing/remembering all the option possible for match case over time

Upvotes: 3

Barmar
Barmar

Reputation: 780787

Keep replacing until there's nothing left to replace:

while True:
    output = re.sub("a\(\s*\d*\s*,\s*\d*\s*\)", "100", input)
    if output == input:
        break
    input = output

Upvotes: 12

Related Questions