My dilemma: I\'m passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there\'s a match in the first regex, do one thing
class RegexStore(object):
_searches = None
def __init__(self, pat_list):
# build RegEx searches
self._searches = [(name,re.compile(pat, re.VERBOSE)) for
name,pat in pat_list]
def match( self, text ):
match_all = ((x,y.match(text)) for x,y in self._searches)
try:
return ifilter(op.itemgetter(1), match_all).next()
except StopIteration, e:
# instead of 'name', in first arg, return bad 'text' line
return (text,None)
You can use this class like so:
rs = RegexStore( (('pat1', r'.*STRING1.*'),
('pat2', r'.*STRING2.*')) )
name,match = rs.match( "MY SAMPLE STRING1" )
if name == 'pat1':
print 'found pat1'
elif name == 'pat2':
print 'found pat2'