簡體   English   中英

使用re.sub()進行遞歸

[英]Recursion with re.sub()

如果我們按如下方式使用它:

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

您可以使用代表多個匹配項的'+'選項而無需while循環。

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

我也往往會忘記正則表達式選項,該選項有時會立即打擊您。 列出/打印並保持在您的面前。 隨着時間的推移,您最終會注意到/記住所有匹配情況的可能選項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM