在python中分配和比较

时间:2014-11-07 22:15:06

标签: python regex match

我需要按顺序执行re.match,并且在匹配情况下我需要匹配的结果来选择组。现在我可以做下一个:

r = re.match('cond1', l)
if r:
    # work with r.group()
else:
    r = re.match('cond2', l)
    if r:
        # work with r.group()
    else:
        r = re.match('cond3', l)
        if r:
            # work with r.group()

等。但我怎么能做得更好?我认为如果像这样执行任务是不可能的:

if r = re.match('cond1', l):
    # work with r.group()
elif r = re.match('cond2', l):
    # work with r.group()
elif r = re.match('cond3', l)
    # work with r.group()

2 个答案:

答案 0 :(得分:3)

你可以使用理解:

r, cond = next((m,c) for (m,c) in ((re.match(cond, line), cond) for cond in ('cond1', 'cond2', 'cond3')) if m)

if cond=='cond1':
    # work with r.group() for cond1
elif cond=='cond2':
    # work with r.group() for cond2

或者如果这看起来太神秘了,那就是一个循环:

for cond in ('cond1', 'cond2', 'cond3'):
    r = re.match(cond, line)
    if r:
        break

if not r:
    # no match
elif cond=='cond1':
    # work with r.group() for cond1
elif cond=='cond2':
    # work with r.group() for cond2

答案 1 :(得分:1)

首先,它通常有助于将事物重构为函数。在这种情况下,它有帮助,因为您可以很容易地从函数返回;你不能在其他代码中间的代码块中提前返回。

def first_match(haystack):
    r = re.match('cond1', haystack)
    if r:
        # work with r.group()
        return
    r = re.match('cond2', l)
    if r:
        # work with r.group()
        return
    r = re.match('cond3', l)
    if r:
        # work with r.group()

所有else位和缩进头痛都消失了。


另外,一般来说,当你问如何将3个或更多的东西连在一起时,正确的答案是弄清楚如何将任意数量的东西链接在一起,并且只需N = 3即可。这通常意味着循环(或隐藏在像map之类的函数中的循环,或递归函数定义等)。例如:

def first_match(exprs, haystack):
    for expr in exprs:
        r = re.match(expr, haystack)
        if r:
            return r

但是,在这种情况下,您尝试做的事实际上是可行的。也许不是一个好主意,但是...正则表达式match对象总是真实的。当然None是假的。所以:

r = re.match('cond1', l) or re.match('cond2', l) or re.match('cond3', l)
if r:
    # work with r.group(), which is the group for whichever matched

但请注意,如果你想要使用真实性,你也可以在循环中这样做:

next(filter(bool, (re.match(cond, l) for cond in ('cond1', 'cond2', 'cond3'))))

最后,您已经在使用正则表达式了,为什么不使用正则表达式?

r = re.match('cond[123]', l)
if r:
    # work with r.group()