我正在分析文件,我想检查每一行与几个复杂的regex。像这样的东西
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
...
这需要进行两次复杂的匹配(这是长文件和长regex:/)
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
...
看起来很奇怪。
正确的方法是什么?
您可以为每个正则表达式所需的操作定义一个函数,并执行如下操作
我喜欢Tim的答案,因为它将每个regex匹配的代码分开,以保持简单。对于我的答案,我不会为每个匹配项放置超过一两行的代码,如果需要更多,请调用单独的方法。
首先,您真的需要使用regexp进行匹配吗?在perl中使用regexp的地方,我经常使用python中的字符串函数(find、startswith等)。
如果确实需要使用regexps,可以使用一个简单的搜索函数来执行搜索,如果返回匹配项,则在返回True之前设置一个store对象来保持匹配。
例如
相关问题 更多 >
编程相关推荐