# regex.py import re # US/Canada phone number rePhone = re.compile(r''' # area code \(?(\d{3})\)? # separator \ * # prefix (\d{3}) # separator [ \-] # suffix (\d{4}) ''', re.VERBOSE) phoneNumbers = [ '(800)555-1212', '650 555 1234', '212-555-9876' ] for num in phoneNumbers: print num, match = rePhone.match(num) if match: print "matches!" else: print "doesn't match" print # Name swapping reName = re.compile(r"(?P[^,]+), +(?P.+)") nameList = [ "Smith, Joseph", "Clinton, William Jefferson", "Bush, George W." ] for name in nameList: print name, "=>", reName.sub(r"\g \g", name)