Hide
Solve a problem – Filter by language, license, keyword, owner, or search text to find code & info fast. Join Siafoo Now or Learn More

Parse U.S. Phone Numbers Atom Feed 0

In Brief Pass a phone number to parsePhoneNumber, it will return a tuple of (Area Code, 3-Digit Trunk, 4-Digit Number, Extension).
# 's
 1"""Parse U.S. phone numbers
2
3This program is part of "Dive Into Python", a free Python book for
4experienced programmers. Visit http://diveintopython.org/ for the
5latest version.
6"""
7
8__author__ = "Mark Pilgrim (mark@diveintopython.org)"
9__version__ = "$Revision: 1.3 $"
10__date__ = "$Date: 2004/05/05 21:57:19 $"
11__copyright__ = "Copyright (c) 2002 Mark Pilgrim"
12__license__ = "Python"
13
14import re
15
16class InvalidPhoneNumber(Exception): pass
17
18phonePattern = re.compile(r"""
19 ^ # match beginning of string
20 \D* # swallow anything that isn't numeric
21 1? # swallow leading 1, if present
22 \D* # swallow anything that isn't numeric
23 (\d{3}) # capture 3-digit area code
24 \D* # swallow anything that isn't numeric
25 (\d{3}) # capture 3-digit trunk
26 \D* # swallow anything that isn't numeric
27 (\d{4}) # capture 4-digit number
28 \D* # swallow anything that isn't numeric
29 (\d*) # capture extension, if present
30 """, re.VERBOSE)
31
32def parsePhoneNumber(phoneNumber):
33 match = phonePattern.search(phoneNumber)
34 if match:
35 return match.groups()
36 else:
37 raise InvalidPhoneNumber, phoneNumber

Pass a phone number to parsePhoneNumber, it will return a tuple of (Area Code, 3-Digit Trunk, 4-Digit Number, Extension).