我的困境:我正在向我的函数传递一个字符串,然后我需要对其执行大量正则表达式操作。逻辑是,如果第一个正则表达式中有匹配项,就做一件事。如果不匹配,则检查与第二个是否匹配并执行其他操作,如果不匹配则检查第三个,依此类推。我可以这样做:
if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
但是,这感觉过于冗长,通常情况下,这意味着有更好的方法我要么忽略了,要么还不知道。
有没有人建议有更好的方法来执行此操作(从代码外观的角度、内存使用的角度或两者都更好)?
最佳答案
一般来说,在这些情况下,您希望使代码“数据驱动”。也就是把重要的信息放在一个容器里,循环遍历。
在您的情况下,重要信息是(字符串、函数)对。
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')
关于python - 如何在 Python 中简洁地级联多个正则表达式语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/597476/