简体   繁体   English

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

[英]Check if a list has one or more strings that match a regex

If need to say 如果需要说

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

I found this powerful construct to extract matching strings from a list: 发现这个强大的构造从列表中提取匹配的字符串:

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

...but this is hard to read and overkill. ......但这很难读懂和矫枉过正。 I don't want the list, I just want to know if such a list would have anything in it. 我不想要列表,我只是想知道这样的列表是否包含任何内容。

Is there a simpler-reading way to get that answer? 是否有更简单的阅读方式来获得答案?

You can simply use any . 你可以简单地使用any Demo: 演示:

>>> 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

use re.match if you want to enforce matching from the start of the string. 如果要从字符串的开头强制执行匹配,请使用re.match

Explanation : 说明

any will check if there is any truthy value in an iterable. any都会检查迭代中是否存在任何真值。 In the first example, we pass the contents of the following list (in the form of a generator): 在第一个例子中,我们传递以下列表的内容(以生成器的形式):

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

which has one match-object which is truthy, while None will always evaluate to False in a boolean context. 它有一个匹配对象,它是真实的,而None总是在布尔上下文中计算为False This is why any will return False for the second example: 这就是为什么any将为第二个示例返回False

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM