如何在Python中简洁地级联多个正则表达式语句

One*_*yon 13 python regex coding-style

我的困境:我正在传递一个字符串,然后我需要执行大量的正则表达式操作.逻辑是如果在第一个正则表达式中匹配,做一件事.如果不匹配,请检查与第二个匹配并执行其他操作,如果不检查第三个,依此类推.我可以这样做:

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.]
Run Code Online (Sandbox Code Playgroud)

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

有没有人建议更好的方法来做到这一点(从代码外观角度,内存使用角度或两者兼而有之)?

dan*_*gph 24

一般来说,在这些情况下,您希望使代码"数据驱动".也就是说,将重要信息放在容器中,然后遍历它.

在您的情况下,重要信息是(字符串,函数)对.

import re

def fun1():
    print('fun1')

def fun2():
    print('fun2')

def fun3():
    print('fun3')

regex_handlers = [
    (r'regex1', fun1),
    (r'regex2', fun2),
    (r'regex3', fun3)
    ]

def example(string):
    for regex, fun in regex_handlers:
        if re.match(regex, string):
            fun()  # call the function
            break

example('regex2')
Run Code Online (Sandbox Code Playgroud)


Mar*_*rot 13

类似的问题从九月回来:你如何将这个正则表达式的习惯用法从Perl翻译成Python?

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

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
Run Code Online (Sandbox Code Playgroud)