tags:

views:

84

answers:

2

Hi. 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.

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:.

Thanks in advance.

+4  A: 
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!'
nosklo
Just what I was looking for, thanks
houbysoft
+6  A: 
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!"
Ned Batchelder
Actually, this is even simpler :)
houbysoft
If you don't need to know which one matched, it's better to bracket them with `(?:regex)` instead of `(regex)`
John Machin