【问题标题】:Check if a list has one or more strings that match a regex检查列表是否有一个或多个与正则表达式匹配的字符串
【发布时间】:2016-04-03 21:10:31
【问题描述】:

如果需要说

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

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

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

...但这很难阅读并且矫枉过正。我不想要这个列表,我只想知道这样的列表中是否有任何内容。

有没有更简单的阅读方式来获得答案?

【问题讨论】:

    标签: python regex list


    【解决方案1】:

    您可以简单地使用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 将检查可迭代对象中是否存在任何真实值。在第一个示例中,我们传递了以下列表的内容(以生成器的形式):

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

    它有一个真实的匹配对象,而None 在布尔上下文中将始终评估为False。这就是为什么 any 将在第二个示例中返回 False 的原因:

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

    【讨论】:

    • 甜蜜而简单的 REPL 示例!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2022-11-12
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多