我需要按顺序做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中执行赋值:
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()
发布于 2014-11-07 22:18:52
你可以使用一种理解:
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
发布于 2014-11-07 22:29:36
首先,将事物重构为函数通常会有所帮助。在这种情况下,它很有帮助,因为您可以很容易地从一个函数提前返回;您不能从其他代码中间的一段代码提前返回。
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()
https://stackoverflow.com/questions/26810994
复制相似问题