Prateek N
Prateek N

Reputation: 19

Optional String Match in Python Regex

I have a code in Python 2.7 which is used in finding information from a flight in a given piece of text. They always come grouped (operators have a standard format and just fill in the blanks and send the message)

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

However I want to 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."

and also

"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."

How do I do it?

Upvotes: 0

Views: 618

Answers (1)

karthik manchala
karthik manchala

Reputation: 13640

Make all new optional with ?. Use the following::

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)

Upvotes: 1

Related Questions