代码之家  ›  专栏  ›  技术社区  ›  leoluk

正则表达式:在列表中搜索

  •  44
  • leoluk  · 技术社区  · 14 年前

    我想根据正则表达式筛选列表中的字符串。

    有比这更好的吗 [x for x in list if r.match(x)] ?

    3 回复  |  直到 10 年前
        1
  •  122
  •   Ma0    7 年前

    您可以创建 在Python3.x或 在Python2.x中使用:

    filter(r.match, list)
    

    转换Python 3.x list(filter(..)) .

        2
  •  188
  •   Mercury    5 年前

    完整示例(Python 3):
    对于Python2.x,请查看下面的注释

    import re
    
    mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
    r = re.compile(".*cat")
    newlist = list(filter(r.match, mylist)) # Read Note
    print(newlist)
    

    印刷品:

    ['cat', 'wildcat', 'thundercat']
    

    filter 已返回列表。在 Python 3.x filter 已更改为返回迭代器,因此必须将其转换为 list (为了看它打印得漂亮)。

    Python 3 code example
    Python 2.x code example

        3
  •  3
  •   Collin Heist    4 年前

    要在不首先编译Regex的情况下执行此操作,请使用 lambda 函数-例如:

    from re import match
    
    values = ['123', '234', 'foobar']
    filtered_values = list(filter(lambda v: match('^\d+$', v), values))
    
    print(filtered_values)
    

    退货:

    ['123', '234']
    

    filter() callable 作为第一个参数,并返回一个列表,其中该callable返回了一个“truthy”值。