使用python中的re.match更好地控制流量

时间:2013-07-18 22:28:56

标签: python regex match

我最近一直在处理正则表达式,我正在寻找一种方法来改进流量控制时必须使用许多正则表达式。

这就是通常的样子。

result = re.match(string, 'C:')
if result:
    #do stuff here
else:
    result2 = re.match(string, 'something else')

if result2:
    #do more stuff
else:
    result3 = re.match(string, 'and again')

 .
 .
 .

我真正想要的是拥有类似的东西。

MatchAndDo(string, regex_list, function_pointer_list)

或者更好的做事方式。

1 个答案:

答案 0 :(得分:1)

您可以使用

完成它
patterns = (
    #(<pattern>, <function>, <do_continue>)
    ('ab', lambda a: a, True),
    ('abc', lambda a: a, False),
)

def MatchAndDo(string, patterns):
    for p in patterns:
        res = re.match(p[0], string)
        if res is None:
            continue

        print "Matched '{}'".format(p[0])
        p[1](p[0]) # Do stuff
        if not p[2]:
            return

MatchAndDo('abc', patterns)

请注意,re.match()匹配字符串http://docs.python.org/2.7/library/re.html?highlight=re.match#re.match

开头的字符
相关问题