How to check the phone number using regex?

by filiberto , in category: Third Party Scripts , 2 days ago

How to check the phone number using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , a day ago

@filiberto 

You can use the following regex pattern to check for a valid phone number format:


^(?d{3})?[-.s]?d{3}[-.s]?d{4}$


This pattern will match phone numbers in the following formats:

  • (123) 456-7890
  • 123-456-7890
  • 123.456.7890
  • 123 456 7890


Here is a simple example in Python on how to use this regex pattern to check a phone number:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import re

def check_phone_number(phone_number):
    pattern = r'^(?(d{3}))?[-.s]?(d{3})[-.s]?(d{4})$'
    
    if re.match(pattern, phone_number):
        print("Valid phone number")
    else:
        print("Invalid phone number")
        
phone_number = "(123) 456-7890"
check_phone_number(phone_number)


You can adjust the regex pattern according to the specific phone number format you are looking for.