Python 使用正则表达式处理成长if条件的更好模式

Python 使用正则表达式处理成长if条件的更好模式,python,regex,Python,Regex,我需要判断每个输入字符串是否符合规则 因此,在该块中,代码将频繁更改或增加 解决这个问题的好模式是什么,以避免我的代码太长 if re.match("(exposurewin_c)(.*?)(_profile_i)", input_str): DO SOMETHING if re.match("....", input_str): DO SOMETHING 首先,如果要根据条件执行的代码段可能很长,则应将其移动到自己的函

我需要判断每个输入字符串是否符合规则

因此,在该块中,代码将频繁更改或增加

解决这个问题的好模式是什么,以避免我的代码太长

if re.match("(exposurewin_c)(.*?)(_profile_i)", input_str):              
    DO SOMETHING

if re.match("....", input_str):              
    DO SOMETHING

首先,如果要根据条件执行的代码段可能很长,则应将其移动到自己的函数中,该函数接受一些参数,然后返回计算值(或值的元组)-这允许单独测试它们,并可将其重新定位到替代模块

其次,使用返回一个“已编译”的正则表达式对象,以节省每次执行的一些计算时间,特别是当进程可能很长或者有许多正则表达式需要匹配时

最后,您可以考虑将所有这些都粘贴到一个2元组列表中,并使用<代码> < < /Cult>循环来遍历所有的条件。我以前也做过类似的事情,这可能会让你开始。 进口稀土

def action_exposure(match, input_str):
    # do something with the match result
    print("exposure caught")
    print(match.groups())

def action_process(match, input_str):
    # do something with the match result
    print("process caught")
    print(match.groups())


raw = [
    ('^exposure:(?P<suffix>[0-9]*)', action_exposure),
    ('^process:(?P<suffix>[0-9]*)', action_process),
]

# compile the raw expression
compiled = [(re.compile(p), f) for p, f in raw]


inputs = """
exposure:3
process:35
somethingelse:3333
exposure:4
"""

for i in inputs.splitlines():
    for regexp, f in compiled:
        match = regexp.match(i)
        if not match:
            continue
        f(match, i)

import re

def action_exposure(match, input_str):
    # do something with the match result
    print("exposure caught")
    print(match.groups())

def action_process(match, input_str):
    # do something with the match result
    print("process caught")
    print(match.groups())


raw = [
    ('^exposure:(?P<suffix>[0-9]*)', action_exposure),
    ('^process:(?P<suffix>[0-9]*)', action_process),
]

# compile the raw expression
compiled = [(re.compile(p), f) for p, f in raw]


inputs = """
exposure:3
process:35
somethingelse:3333
exposure:4
"""

for i in inputs.splitlines():
    for regexp, f in compiled:
        match = regexp.match(i)
        if not match:
            continue
        f(match, i)
一旦你得到了这个模式,你可以简单地定义函数来做一件满足你条件的事情,然后组合模式(或条件),并将其添加到
raw
定义列表中。此外,这将允许更多的代码重用,因为您可以定义多个条件来执行函数(在regex很难执行的情况下)

另外,请注意,我对所做的事情做了一些假设-您确实需要做一些工作来决定如何/哪些参数要传递到函数中,因为这通常需要保持一致,但是当您像这样分解问题时,它将使您更容易思考并更快地找到解决方案

exposure caught
('3',)
process caught
('35',)
exposure caught
('4',)