在python中使用re.match实现更好的流控制
我最近一直在使用正则表达式,我正在寻找一种方法,在必须使用许多正则表达式时改进流控制 这就是事物通常的样子在python中使用re.match实现更好的流控制,python,regex,match,Python,Regex,Match,我最近一直在使用正则表达式,我正在寻找一种方法,在必须使用许多正则表达式时改进流控制 这就是事物通常的样子 result = re.match(string, 'C:') if result: #do stuff here else: result2 = re.match(string, 'something else') if result2: #do more stuff else: result3 = re.match(string, 'and again
result = re.match(string, 'C:')
if result:
#do stuff here
else:
result2 = re.match(string, 'something else')
if result2:
#do more stuff
else:
result3 = re.match(string, 'and again')
.
.
.
我真正想要的是有点像
MatchAndDo(string, regex_list, function_pointer_list)
或者一种更好的做事方式。你可以用
patterns = (
#(<pattern>, <function>, <do_continue>)
('ab', lambda a: a, True),
('abc', lambda a: a, False),
)
def MatchAndDo(string, patterns):
for p in patterns:
res = re.match(p[0], string)
if res is None:
continue
print "Matched '{}'".format(p[0])
p[1](p[0]) # Do stuff
if not p[2]:
return
MatchAndDo('abc', patterns)
模式=(
#(, )
('ab',lambda:a,正确),
('abc',λa:a,假),
)
def MatchAndDo(字符串、模式):
对于模式中的p:
res=re.match(p[0],字符串)
如果res为无:
持续
打印“匹配的”{}“。格式(p[0])
p[1](p[0])#做事
如果不是p[2]:
返回
MatchAndDo('abc',模式)
请注意,
re.match()
匹配字符串开头的字符,因此您想根据匹配的第一个正则表达式采取一些措施吗?是的,我想根据获得的匹配更改我的措施。有时我想继续匹配,有时我只想第一次匹配。我的想法是,有了正则表达式列表和函数指针列表,如果我想在课后继续,我可以直接弹出匹配项。根据你最后的评论更新了我的答案。停止或继续由模式列表中的第三个参数控制