Validate Phone Number Using Regex in Python
Validate a simple phone number format using regular expressions.
IntermediateString ProgramsExample 23 of 25
validate-phone-number-using-regex.py
1# Program to validate phone number using regex23import re45phone = input("Enter phone number: ")67pattern = r"^\+?\d{10,15}$"89if re.match(pattern, phone):10 print("Valid phone number")11else:12 print("Invalid phone number")
Output
Enter phone number: +911234567890 Valid phone number
What's going on
We allow an optional + followed by 10 to 15 digits to represent an international-style phone number.
After this program
If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.