Phone Number Normalization
Definition
In the context of this chapter, a phone number is defined as a sequence of digits that may or may not include an area code. Specifically, in the United States and Canada, a phone number consists of ten digits, typically formatted in various ways such as (NNN) NNN-NNNN, NNN-NNN-NNNN, etc. The task is to normalize these formats to a standard format of 1-NNN-NNN-NNNN, ensuring the area code and exchange code are valid.
Overview
The normalization process involves using regular expressions to match and reformat phone numbers, handling exceptions for invalid formats. The goal is to ensure that all phone numbers conform to a standard format, which includes a country code (1 for the US and Canada) followed by the area code, exchange code, and the subscriber number.
Normalization Process
AI-Generated Code Example
The following Python code demonstrates how to normalize phone numbers using regular expressions:
import re
def normalize_phone_number(phone_number):
phone_number = re.sub(r'\D', '', phone_number) #A
if len(phone_number) not in [10, 11]: #B
raise ValueError("Invalid phone number length")
if not re.match(r'^[2-9][0-8][0-9][2-9]', phone_number[-10:]): #C
raise ValueError("Invalid area code or exchange code")
if len(phone_number) == 10: #D
phone_number = '1' + phone_number
phone_number = re.sub(r'(\d{1})(\d{3})(\d{3})(\d{4})', r'\1-\2-\3-\4', phone_number) #E
return phone_number
# [Test the function.](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-16/112)
phone_numbers = ["+1 223-456-7890",
"1-223-456-7890",
"+1 223 456-7890",
"(223) 456-7890",
"1 223 456 7890",
"999.456.7890",
"1-989-111-2222",
"223.456.7890"]
for number in test_numbers:
try:
normalized_phone_number = normalize_phone_number(number)
print(f'{normalized_phone_number}')
except ValueError as e:
print(f'{number} is not a valid phone number: {e}')
1-223-456-7890
1-223-456-7890
1-223-456-7890
1-223-456-7890
1-223-456-7890
999.456.7890 is invalid: Invalid area code or exchange code
1-989-111-2222 is invalid: Invalid area code or exchange code
1-223-456-7890
#A Removes all non-digit (\D) characters.
#B Length must be 10 or 11.
#C Checks area code and exchange at once.
#D Adds country code if needed.
#E Adds dashes between elements.
Author's Solution
The author's solution uses a function to normalize the numbers as the main regular expression’s parameter and two additional regular expressions in that function to check for illegal numbers.
def return_number(match_obj): #A
# adds country if needed
country = match_obj.group("country") #B
if not country:
country = "1"
# BONUS: raise ValueError if not valid
if not re.match(r"[2-9][0-8]\d", match_obj.group("area") ): #C
raise ValueError("invalid phone number area code {}".format(match_obj.group("area")))
if not re.match(r"[2-9]\d\d", match_obj.group("exch") ): #D
raise ValueError("invalid phone number exchange {}".format(match_obj.group("exch")))
return(f"{country}-{match_obj.group('area')}-{match_obj.group('exch')}-{match_obj.group('number')}")
regexp = re.compile(r"\+?(?P<country>\d{1,3})?[- .]?\(?(?P<area>\d{3})\)?[- .]?(?P<exch>(\d{3}))[- .](?P<number>\d{4})")
for number in test_numbers:
print(regexp.sub(return_number, number)) #E
# [Test ](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-16/112)
phone_numbers = ["+1 223-456-7890",
"1-223-456-7890",
"+1 223 456-7890",
"(223) 456-7890",
"1 223 456 7890",
"999.456.7890",
"1-989-111-2222",
"223.456.7890"]
regexp = re.compile(r"\+?(?P<country>\d{1,3})?[- .]?\(?(?P<area>\d{3})\)?[- .]?(?P<exch>(\d{3}))[- .](?P<number>\d{4})")
for number in test_numbers:
try:
normalized_phone_number = regexp.sub(return_number, number)
print(f'{normalized_phone_number}')
except ValueError as e:
print(f'{number} is not a valid phone number: {e}')
1-223-456-7890
1-223-456-7890
1-223-456-7890
1-223-456-7890
1-223-456-7890
999.456.7890 is invalid: invalid phone number area code 999
1-989-111-2222 is invalid: invalid phone number exchange 111
1-223-456-7890
#A Function passed to regexp.sub method.
#B Add country if needed.
#C Check area code.
#D Check exchange.
#E Call main regexp.
Common Issues
Some solutions may fail to add a country code if it's missing, resulting in incorrect formatting. Additionally, incorrect validation of area codes and exchange codes can lead to errors. It's crucial to ensure that the first digit of the area code and the exchange code is between 2-9, and the second digit of the area code is not 9.
FAQ (Frequently asked questions)
What is a phone number in the context of this chapter?
How is a phone number typically formatted in the United States and Canada?
What is the standard format for phone numbers in the normalization process?
What does the normalization process involve?
How does the phone number normalization function handle non-digit characters?
What happens if the phone number length is not 10 or 11?
How does the function check for valid area code or exchange code?
What does the function do if the phone number is 10 digits long?
How are dashes added to the phone number in the normalization process?