Python:检查列表中是否至less有一个正则expression式匹配string的优雅方法

我有一个python正则expression式列表和一个string。 有没有一个优雅的方式来检查,如果至less有一个正则expression式匹配string? 通过优雅,我的意思是比简单循环所有的正则expression式,并检查他们对string和停止,如果find匹配。

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

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

现在我想在列表中有一些正则expression式,而不仅仅是string,我想知道是否有一个优雅的解决scheme来检查匹配,以取代if string in list:

提前致谢。

 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!" 
 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!' 

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