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

时间:2021-09-02 00:08:02

I have a list of regexes in python, and a string. Is there an elegant way to check if the at least one regex in the list matches the string? By elegant, I mean something better than simply looping through all of the regexes and checking them against the string and stopping if a match is found.

我在python中有一个regexes列表,还有一个字符串。是否有一种优雅的方法来检查列表中至少一个regex是否与字符串匹配?说到优雅,我指的是比简单地遍历所有regexe并在字符串中检查它们并在找到匹配时停止更好的东西。

Basically, I had this code:

基本上,我有这个代码:

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

Now I would like to have some regular expressions in the list, rather than just strings, and I am wondering if there is an elegant solution to check for a match to replace if string in list:.

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

Thanks in advance.

提前谢谢。

3 个解决方案

#1


66  

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


77  

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


2  

A mix of both Ned's and Nosklo's answers. Works guaranteed for any length of list... hope you enjoy

奈德和诺斯克的回答混合在一起。作品保证任何长度的列表…希望你能喜欢

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

#1


66  

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


77  

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


2  

A mix of both Ned's and Nosklo's answers. Works guaranteed for any length of list... hope you enjoy

奈德和诺斯克的回答混合在一起。作品保证任何长度的列表…希望你能喜欢

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