Python 检查列表是否有一个或多个与正则表达式匹配的字符串
如果需要说Python 检查列表是否有一个或多个与正则表达式匹配的字符串,python,regex,list,Python,Regex,List,如果需要说 if <this list has a string in it that matches this rexeg>: do_stuff() …但这很难理解,也太过分了。我不想要这个列表,我只想知道这样的列表中是否有任何内容 有没有更简单的阅读方法来获得答案?你可以简单地使用任意。演示: >>> lst = ['hello', '123', 'SO'] >>> any(re.search('\d', s) for s in ls
if <this list has a string in it that matches this rexeg>:
do_stuff()
…但这很难理解,也太过分了。我不想要这个列表,我只想知道这样的列表中是否有任何内容
有没有更简单的阅读方法来获得答案?你可以简单地使用
任意。演示:
>>> lst = ['hello', '123', 'SO']
>>> any(re.search('\d', s) for s in lst)
True
>>> any(re.search('\d{4}', s) for s in lst)
False
如果要从字符串开始强制匹配,请使用re.match
说明:
any
将检查iterable中是否存在任何真实值。在第一个示例中,我们传递以下列表的内容(以生成器的形式):
甜美而简单的REPL示例!
>>> lst = ['hello', '123', 'SO']
>>> any(re.search('\d', s) for s in lst)
True
>>> any(re.search('\d{4}', s) for s in lst)
False
>>> [re.search('\d', s) for s in lst]
[None, <_sre.SRE_Match object at 0x7f15ef317d30>, None]
>>> [re.search('\d{4}', s) for s in lst]
[None, None, None]