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

2024-10-03 17:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在努力开发一个程序,它将多个正则表达式与一个语句进行匹配:

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!!")

现在,我希望一次只匹配一个正则表达式,如下所示:

^{pr2}$

相反,这两个正则表达式都与语句匹配,如下所示:

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


Tags: torematchlinegroupatmecoffee
1条回答
网友
1楼 · 发布于 2024-10-03 17:26:44

问题是匹配第一个正则表达式的每个字符串也匹配第二个正则表达式(匹配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!!")

相关问题 更多 >