1
所以我有一個程序,對一個說法匹配多個正則表達式摔跤: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!!")
現在,我只想要一個正則表達式匹配的時間,像這樣的:
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
應該是一個合適的比賽,那麼如何阻止其他正則表達式報告比賽?
沒辦法。'*'是個很貪吃的格局,直到你拿出這個方案限制規則,沒有辦法來幫助你,當然,你可以嘗試使用Temre d貪婪的標記,就像['^提醒我((?:??? at)。)*)at((?:(?!at)。)*)$'](https://regex101.com/r/vE4oE2/1),但我不確定它是否適合您。 –