检查列表中是否有一个或多个与正则表达式匹配的字符串

2024-04-20 09:46:36 发布

您现在位置:Python中文网/ 问答频道 /正文

如果需要说

if <this list has a string in it that matches this rexeg>:
    do_stuff()

Ifound从列表中提取匹配字符串的强大构造:

[m.group(1) for l in my_list for m in [my_regex.search(l)] if m]

……但这很难理解,也太过分了。我不想要名单,我只想知道这样的名单里是否有什么。你知道吗

有没有更简单的阅读方法来得到答案?你知道吗


Tags: inforstringifthatmyitthis
1条回答
网友
1楼 · 发布于 2024-04-20 09:46:36

您只需使用any。演示:

>>> 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中是否有任何truthy值。在第一个示例中,我们传递以下列表的内容(以生成器的形式):

>>> [re.search('\d', s) for s in lst]
[None, <_sre.SRE_Match object at 0x7f15ef317d30>, None]

其中有一个匹配对象是truthy,而None在布尔上下文中总是计算为False。这就是第二个例子any返回False的原因:

>>> [re.search('\d{4}', s) for s in lst]
[None, None, None]

相关问题 更多 >