只要正则表达式匹配,python 中的 while 循环 [英] while-loop in python as long as regex matches

查看:42
本文介绍了只要正则表达式匹配,python 中的 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我知道这可能不是在循环中使用正则表达式编辑字符串的最佳方式.只是为了兴趣:我将如何构建一个循环,只要匹配就执行正则表达式模式,在循环中运行并在不再命中时停止?我在 python 中这样做.

Ok, I'm aware that it's probably not the best way to edit a string with regex expressions in loops. Just for the sake of interest: How would I have to build a loop, that executes a regex pattern as long as it matches, run in a loop and stop when it doesn't hit anymore? Im doing this in python.

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

推荐答案

match is not None,因为 match 返回 None根据文档,不匹配.但是您没有在循环中更新 match.你的意思是这样的:

match is not None, since match returns None in case of no match, according to the docs. But you're not updating match in the loop. Did you mean something like:

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

(注意 search 没有 repl 参数)

(Note that search takes no repl argument)

这篇关于只要正则表达式匹配,python 中的 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆