我在python中有一个正则表达式列表,还有一个字符串。有没有一种优雅的方法来检查列表中是否至少有一个正则表达式与字符串匹配?优雅,我指的是比简单地循环所有正则表达式并根据字符串检查它们并在发现匹配时停止更好的方法。
基本上,我有这样的代码:
list = ['something','another','thing','hello']
string = 'hi'
if string in list:
pass # do something
else:
pass # do something else
现在我希望列表中有一些正则表达式,而不仅仅是字符串,我想知道是否有一个优雅的解决方案来检查匹配项以替换if string in list:
。
5条答案
按热度按时间pxq42qpu1#
ifmq2ha22#
unguejic3#
以下是我根据其他答案得出的结论:
mspsb9vt4#
Ned和Nosklo的答案的混合。作品保证任何长度的列表...希望你喜欢
a1o7rhls5#
如果循环遍历字符串,时间复杂度将是O(n),一个更好的方法是将这些正则表达式组合成一个正则trie。