Python:检查列表中是否至少有一个正则表达式与字符串匹配的优雅方法

mklgxw1f  于 2022-12-28  发布在  Python
关注(0)|答案(5)|浏览(130)

我在python中有一个正则表达式列表,还有一个字符串。有没有一种优雅的方法来检查列表中是否至少有一个正则表达式与字符串匹配?优雅,我指的是比简单地循环所有正则表达式并根据字符串检查它们并在发现匹配时停止更好的方法。
基本上,我有这样的代码:

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

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

pxq42qpu

pxq42qpu1#

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

ifmq2ha22#

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

unguejic3#

以下是我根据其他答案得出的结论:

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

mspsb9vt4#

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

a1o7rhls5#

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

相关问题