Python Regular Expression to extract phone number

python-regular-expression-extract-phone-number-feature-image

In this tutorial, we’re gonna look at way to use Python Regular Expression to extract phone number from a text.

Related Post: Python Regular Expression

Python Regular Expression to extract phone number

Import the regex module

All Python regex functions in re module. Remember to import it at the beginning of Python code or any time IDLE is restarted.

Create Regex object

We create a Regex object by passing a string value representing regular expression to re.compile().

To match the phone number pattern:

Get Match object

Regex object has search() method that searches the string that matches to the regex. It returns:
None if the regex pattern is not found
– a Match object if the pattern is found

Get matched text

We call Match object’s group() method to get the actual matched text from the searched string.

In this example, we use parentheses to group the pattern into several groups, so we can call groups() method that returns a tuple of multiple values.

Extract phone number

Now we want the phone number to be in a standard format. So we store it in phoneNumber variable that are built from groups 2, 4, 6, and 10 of the matched text above (area code, first 3 digits, last 4 digits, extension).

Full code



By grokonez | January 5, 2019.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*