too many indentation when checking a string with many regular expressions serially in python

conditional-statements, indentation, python

Solution

regexes = (regex1, regex2, regex3)
for regex in regexes:
    match = re.search(regex, s)
    if match:
        #do stuff
        break

Alternatively (more advanced):

def process1(match_obj):
    #handle match 1

def process2(match_obj):
    #handle match 2

def process3(match_obj):
    #handle match 3
.
.
.
handler_map = ((regex1, process1), (regex2, process2), (regex3, process3))
for regex, handler in handler_map:
    match = re.search(regex, s)
    if match:
        result = handler(match)
        break
else:
    #else condition if no regex matches

Problem

I get deep indentation when I write code like below ``` match = re.search(some_regex_1, s) if match: # do something with match data else: match = re.search(some_regex_2, s) if match: # do something with match data else: match = re.search(soem_regex_3, s) if match: # do something with match data else: # ... # and so on ``` I tried to rewrite as: ``` if match = re.search(some_regex_1, s): # ... elif match = re.search(some_regex_2, s): # ... elif .... # ... ... ``` but Python doesn't allow that syntax. What should I do to avoid deep indentation in this case?

Original source

Related problems