Python正则表达式:只获取一个匹配的表达式

时间:2016-05-04 14:16:39

标签: python regex python-3.x match

所以我正在与一个程序匹配,该程序将多个正则表达式与一个语句匹配:

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应该是正确的匹配,那么如何阻止其他正则表达式报告匹配?

1 个答案:

答案 0 :(得分:1)

问题是匹配第一个正则表达式的每个字符串也匹配第二个正则表达式(匹配at (.*?) .*的任何字符串也匹配.*。所以matchObj2 实际上是匹配

如果要区分这两种情况,当且仅当第一种正则表达不匹配时,才需要应用第二种正则表达式。

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))
elif matchObj2:
   print("matchObj2.group() : ", matchObj2.group())
   print("matchObj2.group(1) : ", matchObj2.group(1))
   print("matchObj2.group(2) : ", matchObj2.group(2))
else:
   print("No match!!")