import re #Sample Msg sample="This is roger. my contact no is 415-555-4242,& 415-555-4243, 416-555-4244" phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') #Search() return first match mob=phoneNumRegex.search(sample) print mob.group() #find all return All matches mob=phoneNumRegex.findall(sample) print mob phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') mob=phoneNumRegex.findall(sample) print mob #for find all our result is set of tuple & each touple consist of 2 group based on our regression mo=phoneNumRegex.search(sample) print 'area code: ',mo.group(1) print 'phone no :',mo.group(2) heroRegex = re.compile (r'Batman|Tina Fey') mo1 = heroRegex.search('Batman and Tina Fey.') print mo1.group() mo2 = heroRegex.search('Tina Fey and Batman.') print mo2.group() mo3=heroRegex.findall('Tina Fey and Batman.') print mo3 batRegex = re.compile(r'Bat(man|mobile|copter|bat)') mo = batRegex.search('Batmobile lost a wheel') print mo.group() mo = batRegex.search('Batbat lost a wheel') print mo.group() batRegex = re.compile(r'Bat(wo)?man') #here "wo" is optional mo1 = batRegex.search('The Adventures of Batman') print mo1.group() mo1 = batRegex.search('The Adventures of Batwoman') print mo1.group() batRegex = re.compile(r'Bat(wo)*man') mo1 = batRegex.search('The Adventures of Batman') print mo1.group() mo1 = batRegex.search('The Adventures of Batwoman') print mo1.group() mo1 = batRegex.search('The Adventures of Batwowowoman') print mo1.group() haRegex = re.compile(r'(Ha){3}') mo1 = haRegex.search('HaHaHa') print mo1.group() haRegex = re.compile(r'(Ha){3,5}') mo1 = haRegex.search('HaHaHaHa') print mo1.group()