How to Match a Phone Number in Python using Regular Expressions



Python


In this article, we show how to match a phone number in Python using regular expressions.

So phone numbers can come in a few different ways, but they should definitely match a certain pattern that pertains to phone numbers.

One way that a phone number can come is, 516-111-1111

Another way that a phone number can come is, (516)111-111

These are standard ways to represent phone numbers in the United States and probably elsewhere as well.

Say you have a website or some type of desktop software or any software really that asks a user for his/her phone number.

How can we verify that this is a correct format for this phone number?

And we can do so using regular expressions.


###-###-#### Format for a Phone Number

First, we'll tackle the format, ###-###-####

We want the user to enter in the format, ###-###-####

If it doesn't appear in this format, we will generate the output, "Invalid phone number"

If it is entered in the above format, we will generate the output, "Valid phone number"

So let's go into this regular expression.



So let's now go over this code.

re is the module in Python that allows us to use regular expressions. So we first have to import re in our code, in order to use regular expressions.

After this, we have a variable, phonenumber, which contains the phone number, 516-111-2222

We then have a variable, named regex, which contains the pattern, "\w{3}-\w{3}-\w{4}"

We then have an if statement, if re.search(regex, phonenumber):

This if statement searches the phone number to see if the number entered matches the regular expression. If so, it prints it's a valid phone number. If not, it prints it's an invalid phone number.

In this example, since 516-111-2222 is a valid phone number, the program prints out, "Valid phone number"

If we typed in a different format, such as ##########, it would print out, "Invalid phone number" because we didn't program the regular expression so that it matches this format.

This is shown below.






(###)###-#### Format for a Phone Number

First, we'll tackle the format, (###)###-####

We want the user to enter in the format, (###)###-####

If it doesn't appear in this format, we will generate the output, "Invalid phone number"

If it is entered in the above format, we will generate the output, "Valid phone number"

So let's go into this regular expression.



Now the phone number must be in the form (###)###-#### in order to be valid.

And this is how we can match a phone number in Python using regular expressions.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...