Проверка номеров телефонов python

Regex for Phone Number Find and Validation in Python

In this tutorial, it’s shown how to find and validate phone numbers in Python using simple examples. We will review different phone number formats which are the most popular.

The best option for search and validation of data like phones numbers, zip codes, identifiers is Regular expression or Regex.

Next, we’ll see the examples to find, extract or validate phone numbers from a given text or string. The article starts with easy examples and finishes with advanced ones.

Step 1: Find Simple Phone Number

Let’s suppose that we need to validate simple phone number formats which don’t change. For example:

The goal is to find all matches for the pattern.
The mentioned solution is very basic and it’s not working for numbers like:

Читайте также:  Mysql escape string для php

In order to deal with those cases the Regex should be improved.

Step 2: Regex for Phone Numbers with a Plus

Often phones numbers are displayed with plus sign like:

This format is matched by next regular expression:

Note that this will catch:

5000-000-0004 will be extracted as 000-000-000. In the next step we will solve this problem.

Step 3: Validate Phone Numbers for Exact Match

If the the format is important and only exact matches are needed like:
000-000-000 , +000-000-000 but not — 5000-000-0004 , +000-000-0004 then we need to add word boundaries to our Regex by adding at the start and the end \b :

Next let’s see a more generic example which covers international and country phone numbers.

Step 4: Validate International Phone Number

It’s difficult to find and test international numbers with 100% accuracy. Analysis of the data might be needed in order to check what formats are present in the text.

One possible solution for validation of international numbers is:

Another regular expression is:

Step 4: Validate US, UK, French phone numbers

For example let’s start with US phone numbers:

can be done with next Regex:

UK or GB numbers like:

can be searched and validated by:

The next simple Regex will work for French numbers:

Step 5: Find phone numbers in different formats

If you like to build a Regex which find various formats you can try with the next one:

The one above will cover most phone numbers but will not work for all.

If the validation is important or additional features are needed like:

  • updates for new formats/countries/regions
  • geographical information related to a phone number
  • timezone information

then we will recommend mature libraries to be used. Good example in this case is the Google’s Java and JavaScript library for parsing, formatting, and validating international phone numbers.

Conclusion

Have in mind that Regex are powerful but you may face performance issues for the complex ones. Try to use simple and understandable Regex. Sometimes you may need to play with flags in order to make it work properly:

Another important note is about using:

We covered most cases of phone validation by using python and Regex.

By using SoftHints — Python, Linux, Pandas , you agree to our Cookie Policy.

Источник

The Simple Way to Validate Phone Numbers in Python

Phone number validation can be very challenging. The phone number formats vary with different countries. Some of them share the same country code. For example, a valid number starts with +1, the country code of the USA, Canada, and Caribbean islands. This helps to avoid an invalid default region. The phone number formats can even vary within the same country. Overall, there are a lot of complexities. It can make validating international phone numbers very challenging and you might come across a validating phone numbers problem. Is there any way to validate phone number Python effortlessly? In this post, you will find all the details.

Don’t reinvent the wheel.
Abstract’s APIs are production-ready now.

Abstract’s suite of API’s are built to save you time. You don’t need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that’s actually valuable for your app or business, and we’ll handle the rest.

How to validate a phone number in Python

You can validate country codes of phone numbers with Regex. However, it is not an efficient solution. You don’t want to create a custom Regex for each of the countries. It will make the process very complex. Fortunately, there is a library that helps you to validate phone numbers in Python easily. It is known as Python Phonenumbers. In this post, you will find the details of using this Python phone number validator to verify phone numbers. Also, you will find the process of getting user-specific geolocation data. If you want to dive into other Python guides, make sure to read about geolocation an IP address in Python or how to validate emails using Python.

Validate with Python PhoneNumbers

You can validate phone numbers with the Python library Phonenumbers using two different methods. Let’s take a look at how we can use the Phone numbers solution.

Validate Phone Number Using the is_possible_number() Method:

1. First, you have to import the phonenumbers library.

2. Create a variable, called string_phone_number. It will contain your ten digit number.

 string_phone_number = "+40032215789" 

3. Then you need to parse the given phone number.

 phone_number = phonenumbers.parse(string_phone_number) 

4. Finally, you have to use the is_possible_number() method to perform the validation. Then you can set up the print output.

 print(phonenumbers.is_possible_number(phone_number)) 

Overall, the code will look like this:

 import phonenumbers my_string_number = "+40021234567" my_number = phonenumbers.parse(my_string_number) print(phonenumbers.is_possible_number(my_number)) 

Validate Phone Number Using the is_valid_number() Method:

1. Import the phonenumbers library.

2. Create the string_phone_number variable. It will contain your phone number.

 string_phone_number = "+40032215789" 

3. Then you have to parse the string_phone_number.

 phone_number = phonenumbers.parse(string_phone_number) 

4. Now, you can utilize the is_valid_number() method to start validating phone number

 print(phonenumbers.is_valid_number(my_number)) 

Overall, the code will look like this with the phonenumber object:

 import phonenumbers my_string_number = "+40021234567" my_number = phonenumbers.parse(my_string_number) print(phonenumbers.is_valid_number(my_number)) 

The Problem with the Two Methods:

As you can see, the only challenge with the above code is the two different results by using the same number. The is_possible_number() method provides False output. But the is_valid_number() method gives you True. What’s the reason behind the difference?

is_possible_number() method verifies the phone number by checking the length of the parsed number. On the other hand, is_valid_number() method looks for the length, phone number prefix, and region to perform a complete validation.

As is_valid_number() method performs full validation, it is a bit slower in delivering the result. So, while iterating over a large list of phone numbers, you can consider using the is_possible_number() method. It will provide results faster. But as you can see in the code examples, the results may not always be right. There is a limitation with the accuracy.

How can you fix the issue? You can try using an API, like Abstract’s Phone Validation API, to validate phone numbers without worrying about the accuracy. You will find the details later in this post.

Getting location from Phone numbers in Python

A phone number is loaded with a variety of information, including user-specific geolocation data. You can use the data to send promotional notifications at the right time in terms of the customer’s time zone. You don’t want to notify the people in the middle of the night. Just pay close attention to formatting phone numbers.

How to Extract Geolocation from the Phone Number in Python

1. First, you have to import phonenumbers library and timezone.

 import phonenumbers from phonenumbers import timezone 

2. Then you have to parse your phone number.

 phone_number = phonenumbers.parse("+447986123456") 

3. Now, you can print the result.

 print(timezone.time_zones_for_number(phone_number)) 

Overall, the code will look like this:

 import phonenumbers from phonenumbers import timezone phone_number = phonenumbers.parse("+447986123456") print(timezone.time_zones_for_number(phone_number)) 
 ('Europe/Guernsey', 'Europe/Isle_of_Man', 'Europe/Jersey', 'Europe/London') 

How to Extract Carrier Name from the Phone Number in Python

You might want to group your phone numbers by their carrier. It will have an impact on your product cost. The Phonenumbers library deals with very easy to extract the name of the carrier from a valid mobile number. You just need to follow these steps:

1. Import phonenumbers library and timezone.

 import phonenumbers from phonenumbers import timezone 

2. Now, you have to parse the phone number.

 phone_number = phonenumbers.parse("+40721234567") 

3. Finally, you have to use the carrier.name_for_number() method to get the carrier’s name of the given phone number.

 print(carrier.name_for_number(phone_number, "en")) 

Overall, the code will look like this:

 import phonenumbers from phonenumbers import carrier phone_number = phonenumbers.parse("+40721234567") print(carrier.name_for_number(phone_number, "en")) 

The Limitation of Extracting Carrier Names with Phonenumbers library

As you can see, the Phonenumbers library has made it very easy for you to extract the name of the carrier. However, there is an issue. In most cases, the Phonenumbers library will be able to provide the name of the carrier accurately for international numbers. However, the result may not be 100% accurate all the time.

Using an API to validate phone numbers

APIs can make the process of validating phone numbers very simple. They enable you to get the job done with just a few lines of code. Also, they help you to extract important data, including carrier, country name, and timezone, with greater accuracy.

You can consider using Abstract’s Phone Validation API. It is lightweight and super-fast. It can help you to determine the validity of phone numbers in 190 countries. It’s very easy to use. You just need to submit the API key and phone number. The Phone Validation API will perform the verification instantly. Also, it provides you with additional data with greater accuracy, including carrier name, line type, city, country, and region.

Let’s try verifying this phone number with Abstract’s Phone Validation API: 14154582468.

 https://phonevalidation.abstractapi.com/v1/ ? api_key = YOUR_UNIQUE_API_KEY & phone = 14154582468 

If the request is successful, you will get this response in JSON format:

Notice that «valid» is set to true, meaning that we entered one of the valid mobile numbers. That means the given phone number is valid. Also, you get a variety of useful data, like country name, registered location, carrier, etc. Just make sure to format phone numbers correctly.

As you can see, the Abstract’s Phone Validation API has made the verification process very simple. It doesn’t require you to write any code from scratch. You just need to get the API key and make a request for verifying the phone number. There is no complexity. You will get the phone number validated instantly.

Wrapping Up

Now, you have learned different methods for validating phone numbers. You can use the Python Phonenumbers library. However, the easiest way is using Abstract’s Phone Validation API. It can help you perform the verification quickly and effortlessly.

Validate international phone numbers using Abstract’s API.

Источник

Оцените статью