How to concisely cascade through multiple regex statements in Python

前端 未结 7 883
天涯浪人
天涯浪人 2020-12-08 05:51

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

7条回答
  •  广开言路
    2020-12-08 06:12

    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'
    

提交回复
热议问题