在python中以串行方式检查具有许多正则表达式的字符串时,会有太多缩进

Le *_*ous 3 python conditional indentation

当我编写如下代码时,我会深陷缩进

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
Run Code Online (Sandbox Code Playgroud)

我试着重写为:

if match = re.search(some_regex_1, s):
    # ...
elif match = re.search(some_regex_2, s):
    # ...
elif ....
    # ...
...
Run Code Online (Sandbox Code Playgroud)

但Python不允许这种语法.在这种情况下,我该怎么做才能避免深度缩进?

Sil*_*Ray 6

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

或者(更高级):

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
Run Code Online (Sandbox Code Playgroud)

  • 而不是'if not result',你可以在for循环中使用'else'块. (3认同)