简体   繁体   English

使用re.sub()进行递归

[英]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() : 现在,例如,我们在a()内部有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. 对不起我的英语不好。

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

You can do it without the while loop using '+' option which stand for multiple match. 您可以使用代表多个匹配项的'+'选项而无需while循环。

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 随着时间的推移,您最终会注意到/记住所有匹配情况的可能选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM