How to concisely cascade through multiple regex statements in Python

前端 未结 7 878
天涯浪人
天涯浪人 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:01

    Similar question from back in september: How do you translate this regular-expression idiom from Perl into Python?

    Using global variables in a module maybe not the best way to do it, but converting it into a class:

    import re
    
    class Re(object):
      def __init__(self):
        self.last_match = None
      def match(self,pattern,text):
        self.last_match = re.match(pattern,text)
        return self.last_match
      def search(self,pattern,text):
        self.last_match = re.search(pattern,text)
        return self.last_match
    
    gre = Re()
    if gre.match(r'foo',text):
      # do something with gre.last_match
    elif gre.match(r'bar',text):
      # do something with gre.last_match
    else:
      # do something else
    

提交回复
热议问题