How to Find Phone Number in Regex Python for Beginners

In this tutorial, make sure you are looking that How to Find Phone Number in Regex Python while the regex in python is working well in the updated version so, guys, the code will provide you the number values in the series of python not only to find the United state of America number but also some changes will be provide you another country number to get from the variable.

So, not the way except regex in python to get the number even it is not easy to do due to python regex is very tough to use.

Read more: How to Count Words, Sentences, Questions, Commas from Paragraph in Python

How to Find Phone Number in Regex Python

First of all, you have to import the regex that means Regular Expression so, after importing it you will able to run the code.

import re

Now, I imported the regular expression in the code so, go to the next move.

Make a variable where you will storage the message or number such as:

wordFile = '''(800)-123-1432
 800 123-1432
 800 123 1432
 123-1432
 '''

Now, I have to break the small breakout that is available in the first number and then the code goes to the next move and check is it available right or not? and then goes to the next number such as space that has taken in the code after it runs three numbers then space and – need to break it out.

Make one more variable to do the code.

number = re.compile(r'''(((?\d{3})?)?(\s?-?)?\d{3}(\s?-?)?\d{4})''')

The number is a variable. And Re has imported by the above code so, here we use. Compile is a function of regex in python and then r means read the code and then one small bracket to start the coding.

Make one more variable in the same coding that would name is the result.

result = number.findall(wordFile)

Result as a variable, the number we already used as a variable in the above code, findall is a built-in function of regex python, and wordFile is a name of the variable where we have stored the number.

It will find in the wordFile and give you all the value in the result variable then you just go and call it.

We have to use the for loop in it.

for i in result:
      ori, n1, n2, n3 = i
      print(ori)

It is for removing the spaces, and – so, here we used the trick. I have to write that Find Phone Number in Regex Python for Beginners. Not for you and me, it is for beginners.

Output Find Phone Number in Regex Python :

 import re

 wordFile = '''(800)-123-1432  800 123-1432  800 123 1432  123-1432  ''' 
 number = re.compile(r'''(((?\d{3})?)?(\s?-?)?\d{3}(\s?-?)?\d{4})''')

  result = number.findall(wordFile)

  for i in result:       ori, n1, n2, n3 = i       print(ori) 
Find Phone Number in Regex

Leave a Comment