条件中的python正则表达式匹配

编程入门 行业动态 更新时间:2024-10-14 12:21:19
本文介绍了条件中的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正则表达式匹配

本文发布于:2023-11-22 14:39:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617840.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   正则表达式   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!