How to concisely cascade through multiple regex statements in Python

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

    Generally speaking, in these sorts of situations, you want to make the code "data driven". That is, put the important information in a container, and loop through it.

    In your case, the important information is (string, function) pairs.

    import re
    
    def fun1():
        print('fun1')
    
    def fun2():
        print('fun2')
    
    def fun3():
        print('fun3')
    
    regex_handlers = [
        (r'regex1', fun1),
        (r'regex2', fun2),
        (r'regex3', fun3)
        ]
    
    def example(string):
        for regex, fun in regex_handlers:
            if re.match(regex, string):
                fun()  # call the function
                break
    
    example('regex2')
    

提交回复
热议问题