Guides
Last Updated Aug 03, 2023

Phone Number Python Regex: How to Verify Numbers with Python and Regex

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Phone numbers are becoming increasingly important in modern app development. With the majority of users now accessing sites and apps from their mobile devices, phone numbers have become the primary method of user authentication, verification, and authorization.

Phone numbers and email addresses are some of the most secure means we have of authenticating users. For that reason, it's important to know how to use them in your application.

Phone Number Verification

The first step in using phone numbers in user authentication is verifying the phone numbers. This means determining that the string a user provided in the input is, in fact, a phone number and that it is an active number capable of receiving texts and calls.

In this tutorial, we'll look at using Regex and Python to verify that a given string matches what we expect a phone number to look like. We will then use a free API service to find out whether the phone number is currently active, and get some information about the number, including carrier and location.

This tutorial will not cover using a service like Twilio to send a code to a mobile device to determine that it belongs to the user. It will also not cover the basics of getting started with Python. If you need a refresher on Python and how to get started, we recommend checking the docs.

Let’s send your first free
API
Phone Validation API
call
See why the best developers build on Abstract
Get your free api

Regex Pattern Matching Phone Numbers

The first step in performing a Regex check with Python is to create a regex pattern that matches phone numbers. Then we will use the built-in Python Regex module to test the string that a user provides against the Regex pattern we have created.

Common Problems With Phone Number Validation

Similar to matching email addresses, matching phone numbers with Regex is not recommended in production. Phone number validation with a regular expression is tricky, particularly when your app must handle international numbers.

Number Length

As mentioned, valid US phone numbers are 10 digits long (when the area code is included and the +1 is not), but a valid Mexican phone number is 12 digits long. In some countries, phone numbers are longer. The maximum length for a international phone number is 15 digits, according to the International Telecommunication Union (ITU.)

Delimiters

Delimiters (the characters that come between the numbers in phone numbers) are also different all over the world. Some countries use the em-dash (-), while others use a period or dot (.) and still, others use parentheses, tildes, or other separators. The way numbers are grouped together in phone numbers also differs from country to country.

User Error

All these differences lead to a large margin for user error. Some users will try to include dashes in their phone numbers while others will not. Some users will include country codes. Some will include spaces whereas others will not. Some users might omit the area code or the +1 from a US number.

The Problem With Using Regex to Match Phone Numbers

All that being said, you will almost immediately come up against these problems when using a Regex pattern to match phone numbers because there are many different ways to format a phone number. Writing a single specific pattern to capture all the characters and possibilities is impossible.

For this reason, we don't recommend relying solely on Regex phone number pattern matching to handle parsing phone numbers and performing your phone number validation. Using a Regular expression in tandem with a dedicated third-party service is the most robust way to check for a valid number.

Parsing Phone Numbers

One recommended method for dealing with international phone numbers and other phone number matching issues is to strip all the characters that aren't numeric digits from the string before you begin.

Unfortunately, this method doesn't work very well either, as all you are left with after you remove anything that isn't a numeric digit is a string of numbers that could be between 7 and 15 characters long. This doesn't give you much to work with to determine whether or not the string is a valid number.

A Good Regex Pattern for Matching Phone Numbers

Let's take a look at some basic regular expression syntax that matches US phone numbers. Keep in mind that this pattern can only be relied upon to match US phone numbers. Here is the pattern:



^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$

This specific pattern will match US phone numbers in the following formats:


123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890

Let's look at how we would use this regular expression in our Python code.



import re

phone_regex = '^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$'
phone_number = '(123) 456-7890'
match = re.search(phone_regex, phone_number)

print(match)

Here, we imported the Python re module, which provides methods for working with regular expressions. We created a variable to hold our phone number pattern, and another variable to hold our phone number.

Next, we used the re.search function to search the input string for a match to the regular expression. The re.search function searches the input string from the beginning of the string and creates a Match object if a matching substring is found.

The result of printing the match object will look like this:



<re.Match object; span=(0, 14), match='(123) 456-7890'>

The Match object contains information about the search and the result. The span field indicates the positions in the string where the match started and ended. The match field indicates the match that was found. If the match was a substring of the input string, a group field will indicate where the matched group was found.

If no match is found, re.search will return null. You can therefore examine the result of the re.search function to determine if input phone numbers are valid: a valid number will return a match, while an invalid phone number will return null.

Validating Phone Numbers With an API

Short of sending an SMS to a number to determine its validity (which you should always do as part of your phone number verification process) the best way to check for valid or invalid phone numbers is to use a dedicated third-party library or API.

One such service is AbstractAPI's Free Phone Number Verification API. This API provides an endpoint to which you can send a phone number string and receive a response telling you whether or not the string is a valid phone number.

AbstractAPI performs several checks to determine the validity of the number. First, they check the number against a regular expression. Next, they verify the number against a regularly updated database of phone numbers to determine whether the number is a disposable number, VOIP, a free phone number, or another type of low-quality number.

The API returns a JSON object a validity boolean and information about the number's carrier and location information.

Let's look at how we can use AbstractAPI's Free Phone Validation endpoint to check the validity of a provided number.

Acquire an API Key

Go to the Phone Validation API Get Started page and click the blue “Get Started” button.

You’ll need to sign up with an email address and password to acquire an API key. If you already have an AbstractAPI account, you'll be asked to log in. Next, you’ll land on the API’s homepage, where you’ll see options for documentation, pricing, and support.

Look for your API key, which will be listed on this page. Every Abstract API has a unique key, so even if you’ve used a different Abstract API endpoint before, this key will be unique.

Send a Request to the API

We'll use the built-in Python requests module to send a POST request to the API endpoint with the number for validation.



import requests

api_url = "https://phonevalidation.abstractapi.com/v1/"
api_key = YOUR_API_KEY

def validate_phone_number(phone_number):
   params = {
       'api_key': api_key,
       'phone': phone_number
   }
  try:
      response = requests.get(api_url, params=params)
      print(response.content)
  except requests.exceptions.RequestException as api_error:
      print(f"There was an error contacting the Phone Number API: {api_error}")
      raise SystemExit(api_error)

The response sent back by the API will look something like this:



{
  "phone": "14152007986",
  "valid": true,
  "format": {
    "international": "+14152007986",
    "local": "(415) 200-7986"
  },
  "country": {
    "code": "US",
    "name": "United States",
    "prefix": "+1"
  },
  "location": "California",
  "type": "mobile",
  "carrier": "T-Mobile USA, Inc."
}

From here, all we need to do is extract the valid field from the response object and use its value to determine the validity of the number.

The best part about the AbstractAPI endpoint is that it works across different programming languages. Simply toggle the language choice in the sandbox on your dashboard to see options for Javascript, Ruby, Node, Java, and more.

Conclusion

In this tutorial, we looked at how to use Regex and Python to determine the validity of phone numbers. We also discussed why relying on Regex patterns for verification of your phone numbers isn't a good idea in production. We then looked at AbstractAPI's Free Phone Validation endpoint as an alternative to regular expressions.

FAQs

How do you write Regex in a phone number in Python?

Matching phone numbers, like matching email addresses, is tricky with regular expressions. There is no specific Regex pattern that will match all international numbers. Phone numbers all over the world have different formats, delimiters, grouping mechanisms, and lengths.

For that reason, it's recommended that you use a library or service to validate phone numbers in your web or mobile application, and don't rely solely on a regular expression.

How do you validate a phone number in Python?

There are several ways to validate phone numbers in Python. You can check them against a regular expression to find out whether the phone numbers are properly formatted (be aware that this is error-prone and not recommended for production apps.) You can use a library like phonenumbers. Finally, you can rely on a third-party API or service like AbstractAPI to validate phone numbers for you and return a JSON response with the result.

What is phone numbers library in Python?

The phone numbers library is an open-source Python module that facilitates cleaning, parsing, examining, and validating phone numbers. It is a Python port of the Google libphonenumbers library.

4.6/5 stars (15 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Phone Validation API
API
key now
Validate phone numbers instantly using Abstract's phone verification API.
get started for free

Related Articles

Get your free
API
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required