【发布时间】:2011-08-18 19:04:54
【问题描述】:
我正在解析文件,我想根据一些复杂的正则表达式检查每一行。像这样的
if re.match(regex1, line): do stuff
elif re.match(regex2, line): do other stuff
elif re.match(regex3, line): do still more stuff
...
当然,要做这些事情,我需要匹配对象。我只能想到三种可能性,每一种都有不足之处。
if re.match(regex1, line):
m = re.match(regex1, line)
do stuff
elif re.match(regex2, line):
m = re.match(regex2, line)
do other stuff
...
这需要进行两次复杂的匹配(这些是长文件和长正则表达式:/)
m = re.match(regex1, line)
if m: do stuff
else:
m = re.match(regex2, line)
if m: do other stuff
else:
...
当我越来越缩进时,这变得很糟糕。
while True:
m = re.match(regex1, line)
if m:
do stuff
break
m = re.match(regex2, line)
if m:
do other stuff
break
...
这看起来很奇怪。
这样做的正确方法是什么?
【问题讨论】:
标签: python regex conditional