python正则表达式只匹配第一个,Python正则表达式:仅获取一个匹配的表达式

So I'm wrestling with a program that matches multiple regular expressions against one statement:

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

Now, I want only one regex to match at a time, like this:

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

Instead, both the regexes match up to the statement, like this:

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

Only matchObj should be a proper match here, so how do I stop the other regexes from reporting a match?

解决方案

The problem is that every string matching the first regex also matches the second one (anything that matches at (.*?) .* also matches .*. So matchObj2 is in fact a proper match.

If you want to distinguish these two situations, you need to apply the second regex if and only if the first one produces no 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))

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值