Skip to main content
 首页 » 编程设计

python之使用 re.sub() 递归

2025年05月04日8xing901022

如果我们这样使用它:

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

我们得到:

>> "100" 

现在,例如我们在 a() 中有 a():

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

我们得到:

>> 'a(30, 100)' 

但是我想要这样的东西:

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

对不起我的英语。

请您参考如下方法:

不断更换,直到没有东西可以更换为止:

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