如何在Python中通过多个正则表达式语句简洁地级联 [英] How to concisely cascade through multiple regex statements in Python

查看:114
本文介绍了如何在Python中通过多个正则表达式语句简洁地级联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的困境:我传递我的函数一个字符串,我需要然后执行大量的正则表达式操作。逻辑是如果在第一个正则表达式中有匹配,做一件事。如果没有匹配,检查与第二个匹配,并做别的事情,如果不检查第三,等等。我可以这样做:

My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:

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

然而,这感觉不必要的冗长,通常情况下,这意味着有一个更好的方式,我可以忽略或不知道。

However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.

有一个建议,以更好的方式来做到这一点(从代码外观的立场,内存使用的立场,或两者)。

Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?

推荐答案

9月份的类似问题:如何将这个正则表达式从Perl转换为Python?

Similar question from back in september: How do you translate this regular-expression idiom from Perl into Python?

在模块中使用全局变量可能不是最好的方法,但将其转换为类:

Using global variables in a module maybe not the best way to do it, but converting it into a class:

import re

class Re(object):
  def __init__(self):
    self.last_match = None
  def match(self,pattern,text):
    self.last_match = re.match(pattern,text)
    return self.last_match
  def search(self,pattern,text):
    self.last_match = re.search(pattern,text)
    return self.last_match

gre = Re()
if gre.match(r'foo',text):
  # do something with gre.last_match
elif gre.match(r'bar',text):
  # do something with gre.last_match
else:
  # do something else

这篇关于如何在Python中通过多个正则表达式语句简洁地级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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