How to concisely cascade through multiple regex statements in Python

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

    I had the same problem as yours. Here´s my solution:

    import re
    
    regexp = {
        'key1': re.compile(r'regexp1'),
        'key2': re.compile(r'regexp2'),
        'key3': re.compile(r'regexp3'),
        # ...
    }
    
    def test_all_regexp(string):
        for key, pattern in regexp.items():
            m = pattern.match(string)
            if m:
                # do what you want
                break
    

    It´s a slightly modified solution from the answer of Extracting info from large structured text files

提交回复
热议问题