question archive Exercise 5 - Phone Number Validator Phone numbers in the USA follow a set pattern, which can be broken down into the following parts: A optional three-digit area code
Subject:Computer SciencePrice:2.86 Bought4
Exercise 5 - Phone Number Validator
Phone numbers in the USA follow a set pattern, which can be broken down into the following parts:
For example, valid phone numbers would include (102) 345-6789, 987 6543, and (505)5555555, but not (121) 222-2222, (3) 3333333, or 4444-4444.
Write code using regular expressions that will take a phone number and check to see if it is valid. (Right now, don't worry about the international code +1.)
import re number = input("Enter number\n") #Use findall function to locate matches #findall returns a list containing all matches #returns False if there is no match valid = re.findall("((\([0-9][0-1][0-9]\)|[0-9][0-1][0-9])\s)?[0-9]{3}[\s|-][0-9]{4}", number) #Checks if there is a match if valid: if len(valid[0][0]) > 0: print("Valid\n") else: print("Invalid\n") else: print("Invalid\n")
Step-by-step explanation
Regex used:
((\([0-9][0-1][0-9]\)|[0-9][0-1][0-9])\s)?[0-9]{3}[\s|-][0-9]{4}
Breakdown of regex:
Regex for the area code:
((\([0-9][0-1][0-9]\)|[0-9][0-1][0-9])\s)?
\([0-9][0-1][0-9]\) This one (A) matches to any 3 digit number with the middle digit being 0 or 1 and enclosed in parentheses. The \( is to include the parentheses
[0-9][0-1][0-9]) This one (B) is for the area code that doesn't have parentheses
Both of these are enclosed to look like this ((A|B)\s)?
(A|B) means that it can match to either A or B.
\s matches to a whitespace
Everything inside a ()? is optional.
Regex for the last 7 digits:
[0-9]{3}[\s|-][0-9]{4}
This is a lot simpler.
[0-9] matches to any single digit from 0 to 9
{} is a quantifier
[0-9]{3} matches to any 3 digit number whose digits are from 0-9
[\s|-] matches to either a whitespace or a dash
[0-9]{4} matches to any 4 digit number whose digits are from 0-9