【发布时间】:2010-01-08 14:28:21
【问题描述】:
我需要针对多个(排他性 - 意味着匹配其中一个的字符串不能匹配任何其他)正则表达式尝试一个字符串,并根据它匹配的一个执行不同的代码。我目前拥有的是:
m = firstre.match(str)
if m:
# Do something
m = secondre.match(str)
if m:
# Do something else
m = thirdre.match(str)
if m:
# Do something different from both
除了丑陋之外,此代码匹配所有正则表达式,即使它匹配了其中一个(比如 firstre),这是低效的。我尝试使用:
elif m = secondre.match(str)
但了解到在 if 语句中不允许赋值。
有没有一种优雅的方式来实现我想要的?
【问题讨论】:
标签: python regex switch-statement