gpt4 book ai didi

python - 在 python 中连续检查具有许多正则表达式的字符串时缩进太多

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:47 25 4
gpt4 key购买 nike

当我写如下代码时,我得到了很深的缩进

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

我试着重写为:

if match = re.search(some_regex_1, s):
# ...
elif match = re.search(some_regex_2, s):
# ...
elif ....
# ...
...

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

最佳答案

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

或者(更高级):

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

关于python - 在 python 中连续检查具有许多正则表达式的字符串时缩进太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10690654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com