簡體   English   中英

只要正則表達式匹配,Python中的while循環

[英]while-loop in python as long as regex matches

好的,我知道這可能不是在循環中使用正則表達式編輯字符串的最佳方法。 僅出於興趣的考慮:我將如何構建一個循環,只要匹配就執行一個正則表達式模式,循環運行並在不再命中時停止運行? 我在python中這樣做。

match = re.search(r'pattern, repl, str)
while match (is True, == True?):
   sub = re.sub(r'pattern, repl, str)
else:
   Do something else

根據docsmatch is not None ,因為在沒有匹配的情況下match返回None 但是您不會在循環中更新match 您的意思是:

match = re.search(pattern, repl, str)
while match is not None:
    str = re.sub(pattern, repl, str)
    match = re.search(pattern, str)

(請注意, search不包含repl參數)

暫無
暫無

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

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