【发布时间】:2016-08-30 01:13:26
【问题描述】:
所以我正在努力解决一个将多个正则表达式与一个语句匹配的程序:
import re
line = "Remind me to pick coffee up at Autostrada at 4:00 PM"
matchObj = re.match( r'Remind me to (.*) at (.*?) at (.*?) .*', line, re.M|re.I|re.M)
matchObj2 = re.match( r'Remind me to (.*) at (.*?) .*', line, re.M|re.I)
if matchObj:
print("matchObj.group() : ", matchObj.group())
print("matchObj.group(1) : ", matchObj.group(1))
print("matchObj.group(2) : ", matchObj.group(2))
print("matchObj.group(3) :", matchObj.group(3))
else:
print("No match!!")
if matchObj2:
print("matchObj2.group() : ", matchObj2.group())
print("matchObj2.group(1) : ", matchObj2.group(1))
print("matchObj2.group(2) : ", matchObj2.group(2))
else:
print("No match!!")
现在,我希望一次只匹配一个正则表达式,如下所示:
matchObj.group() : Remind me to pick coffee up at Autostrada at 4:00 PM
matchObj.group(1) : pick coffee up
matchObj.group(2) : Autostrada
matchObj.group(3) : 4:00
相反,两个正则表达式都与语句匹配,如下所示:
matchObj.group() : Remind me to pick coffee up at Autostrada at 4:00 PM
matchObj.group(1) : pick coffee up
matchObj.group(2) : Autostrada
matchObj.group(3) : 4:00
matchObj2.group() : Remind me to pick coffee up at Autostrada at 4:00 PM
matchObj2.group(1) : pick coffee up at Autostrada
matchObj2.group(2) : 4:00
这里只有 matchObj 应该是正确的匹配项,那么如何阻止其他正则表达式报告匹配项?
【问题讨论】:
-
没办法。
.*是一个非常贪婪的模式。在您为这种情况提出限制规则之前,没有办法帮助您。当然,您可以尝试使用经过调整的贪婪令牌,例如^Remind me to ((?:(?! at ).)*) at ((?:(?! at ).)*)$,但我不确定它是否适合您。
标签: python regex python-3.x match