sun*_*ica 5 python regex switch-statement
我需要尝试一个字符串对多个(独占 - 意味着匹配其中一个的字符串不能匹配任何其他)正则表达式,并根据它匹配的代码执行不同的代码.我现在拥有的是:
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
Run Code Online (Sandbox Code Playgroud)
除了丑陋之外,这个代码与所有正则表达式相匹配,即使它匹配其中一个(比如firstre),这是低效的.我试着用:
elif m = secondre.match(str)
Run Code Online (Sandbox Code Playgroud)
但是我知道if语句中不允许赋值.
有没有一种优雅的方式来实现我想要的?
def doit( s ):
# with some side-effect on a
a = []
def f1( s, m ):
a.append( 1 )
print 'f1', a, s, m
def f2( s, m ):
a.append( 2 )
print 'f2', a, s, m
def f3( s, m ):
a.append( 3 )
print 'f3', a, s, m
re1 = re.compile( 'one' )
re2 = re.compile( 'two' )
re3 = re.compile( 'three' )
func_re_list = (
( f1, re1 ),
( f2, re2 ),
( f3, re3 ),
)
for myfunc, myre in func_re_list:
m = myre.match( s )
if m:
myfunc( s, m )
break
doit( 'one' )
doit( 'two' )
doit( 'three' )
Run Code Online (Sandbox Code Playgroud)