【问题标题】:Better flow control with re.match in python在 python 中使用 re.match 更好地控制流
【发布时间】:2013-07-18 02:08:21
【问题描述】:

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

这就是通常的样子。

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)

或者更好的做事方式。

【问题讨论】:

  • 那么您想根据第一个匹配的正则表达式采取一些措施吗?
  • 是的,我想根据我得到的匹配来更改我的操作。有时我想继续匹配,有时我只想要第一个匹配。我的想法是,如果我想继续后记,我可以使用 regex_list 和 function_pointer_list 弹出匹配项。
  • 根据您的最后评论更新了我的答案。停止或继续由模式列表中的第三个参数控制

标签: python regex match


【解决方案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开头的字符

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 2010-10-10
    • 2019-07-23
    • 2023-03-24
    相关资源
    最近更新 更多