Python Regex中的可选字符串匹配

时间:2015-06-13 07:28:51

标签: python regex

我在Python 2.7中有一个代码,用于从给定文本中的航班中查找信息。它们总是分组(运营商具有标准格式,只需填写空白并发送消息)

import re

line = "JetMobile:Your flight 9W448 on 14Jan2015 is expected to leave BLR at 19:00 hrs, reach BOM at 20:42 hrs. Download our Mobile App from http://m.jetairways.com/mobileapps for booking(s), flight status, check-in and more."

matchObj = re.match( r'JetMobile\:Your flight (.*?) on (.*?) is expected to leave (.*?) at (.*?) hrs, reach (.*?) at (.*?) hrs\. Download our Mobile App from (.*?) for booking\(s\), flight status, check-in and more\.', 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!!"

但我想匹配

"JetMobile:Your flight 9W448 on 14Jan2015 is expected to leave BLR at 19:00 hrs, reach BOM at 20:42 hrs. Download our Mobile App from http://m.jetairways.com/mobileapps for booking(s), flight status, check-in and more."

以及

"JetMobile:Your flight 9W448 on 14Jan2015 is expected to leave BLR at 19:00 hrs, reach BOM at 20:42 hrs. Download our all new Mobile App from http://m.jetairways.com/mobileapps for booking(s), flight status, check-in and more."

我该怎么做?

1 个答案:

答案 0 :(得分:1)

all new选择?。使用以下::

matchObj = re.match( r'JetMobile\:Your flight (.*?) on (.*?) is expected to leave (.*?) at (.*?) hrs, reach (.*?) at (.*?) hrs\. Download our (?:all new )?Mobile App from (.*?) for booking\(s\), flight status, check-in and more\.', line, re.M|re.I)