如何在Python中搜索正则表达式匹配?
发布时间:2020-12-16 21:36:31 所属栏目:Python 来源:网络整理
导读:我需要尝试一个字符串对多个(独占 – 意味着匹配其中一个的字符串不能匹配任何其他)正则表达式,并根据它匹配的代码执行不同的代码.我现在拥有的是: m = firstre.match(str)if m: # Do somethingm = secondre.match(str)if m: # Do something elsem = thirdr
我需要尝试一个字符串对多个(独占 – 意味着匹配其中一个的字符串不能匹配任何其他)正则表达式,并根据它匹配的代码执行不同的代码.我现在拥有的是:
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语句中不允许赋值. 有没有一种优雅的方式来实现我想要的? 解决方法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',m def f3( s,m ): a.append( 3 ) print 'f3',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' ) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |