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

python:检查列表中是否至少有一个regex匹配字符串的优雅方法

  •  47
  • houbysoft  · 技术社区  · 16 年前

    我有一个python中的regex列表和一个字符串。是否有一种优雅的方法来检查列表中的至少一个regex是否与字符串匹配?优雅,我指的是比简单地循环遍历所有正则表达式并对照字符串检查它们并在找到匹配项时停止要好的东西。

    基本上,我有这样的代码:

    list = ['something','another','thing','hello']
    string = 'hi'
    if string in list:
      pass # do something
    else:
      pass # do something else
    

    现在,我希望列表中有一些正则表达式,而不仅仅是字符串,我想知道是否有一个优雅的解决方案来检查是否要替换匹配项 if string in list: .

    事先谢谢。

    5 回复  |  直到 7 年前
        1
  •  73
  •   Ned Batchelder    16 年前
    import re
    
    regexes = [
        "foo.*",
        "bar.*",
        "qu*x"
        ]
    
    # Make a regex that matches if any of our regexes match.
    combined = "(" + ")|(".join(regexes) + ")"
    
    if re.match(combined, mystring):
        print "Some regex matched!"
    
        2
  •  82
  •   nosklo    16 年前
    import re
    
    regexes = [
        # your regexes here
        re.compile('hi'),
    #    re.compile(...),
    #    re.compile(...),
    #    re.compile(...),
    ]
    
    mystring = 'hi'
    
    if any(regex.match(mystring) for regex in regexes):
        print 'Some regex matched!'
    
        3
  •  4
  •   Anderas    9 年前

    Ned和Nosklo答案的混合。工程保证清单的任何长度…希望你喜欢

    import re   
    raw_lst = ["foo.*",
              "bar.*",
              "(Spam.{0,3}){1,3}"]
    
    reg_lst = []
    for raw_regex in raw_lst:
        reg_lst.append(re.compile(raw_regex))
    
    mystring = "Spam, Spam, Spam!"
    if any(compiled_reg.match(mystring) for compiled_reg in reg_lst):
        print("something matched")
    
        4
  •  2
  •   user5056973    7 年前

    以下是我根据其他答案所做的努力:

    raw_list = ["some_regex","some_regex","some_regex","some_regex"]
    reg_list = map(re.compile, raw_list)
    
    mystring = "some_string"
    
    if any(regex.match(mystring) for regex in reg_list):
        print("matched")
    
        5
  •  1
  •   ospider    7 年前

    如果循环遍历字符串,则时间复杂性将为O(n)。更好的方法是将这些正则表达式组合为正则表达式trie。