条件中的python正则表达式匹配 [英] Python regex matching in conditionals

查看:49
本文介绍了条件中的python正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析文件,我想针对一些复杂的正则表达式检查每一行.像这样

I am parsing file and I want to check each line against a few complicated regexs. Something like this

if re.match(regex1, line): do stuff
elif re.match(regex2, line): do other stuff
elif re.match(regex3, line): do still more stuff
...

当然,要做这些事情,我需要匹配对象.我只能想到三种可能性,每种可能性都有待改进.

Of course, to do the stuff, I need the match objects. I can only think of three possibilities, each of which leaves something to be desired.

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
...

这需要进行两次复杂的匹配(这些都是长文件和长正则表达式:/)

which requires doing the complicated matching twice (these are long files and long regex :/)

m = re.match(regex1, line)
if m: do stuff
else:
    m = re.match(regex2, line)
    if m: do other stuff
    else:
       ...

随着我越来越缩进,这变得很糟糕.

which gets terrible as I indent further and further.

while True:
    m = re.match(regex1, line)
    if m:
        do stuff
        break
    m = re.match(regex2, line)
    if m:
        do other stuff
        break
    ...

看起来很奇怪.

什么是正确的方法?

推荐答案

您可以为每个正则表达式所需的操作定义一个函数,并执行类似的操作

You could define a function for the action required by each regex and do something like

def dostuff():
    stuff

def dootherstuff():
    otherstuff

def doevenmorestuff():
    evenmorestuff

actions = ((regex1, dostuff), (regex2, dootherstuff), (regex3, doevenmorestuff))

for regex, action in actions:
    m = re.match(regex, line)
    if m: 
        action()
        break

这篇关于条件中的python正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆