Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract US phone numbers from a string

Tags:

regex

php

I am trying to extract US only phone numbers from a string.

I have looked around the web/SO but have not found any suitable solution for my needs.

To be honest, I have 2.5 years of experience in Web Programming but I suck at RegEX.

Here is only RegEX I wrote (\d{3}+\-\d{3}+\-\d{4}+)

but it only detects 589-845-2889

Here are phone numbers I want to extract.

589-845-2889

(589)-845-2889

589.845.2889

589 845 2889

5898452889

(589) 845 2889

Please tell me how can I achieve this feat in single Regex for PHP.

EDIT:

If you feel any other format of US number a user can enter, also mention that as well, and include that in RegEX as well.

P.S:

Actually I am trying to scrape Craiglist and user may have posted their phone number in any possible format.

like image 641
Umair Ayub Avatar asked Jul 05 '16 11:07

Umair Ayub


People also ask

How do I extract a phone number from a string in Python?

We can use the phonenumbers library to extract phone numbers from a text with Python. The handy phonenumbers. PhoneNumberMatcher() method iterates the text and extract any phone number, whether it is in a domestic or international format.

Are phone numbers stored as strings?

Mobile phone numbers are not stored as integers, as the integer data type holds values that have the potential to be used in calculations. There is no context for using a mobile phone number as part of a calculation, so it is stored as a STRING value.


2 Answers

In PHP (PCRE) you can use this regex based on conditional subpatterns:

(\()?\d{3}(?(1)\))[-.\h]?\d{3}[-.\h]?\d{4}

RegEx Demo

  • (\()? matches optional ( and captures it in group #1
  • (?(1)\)) is conditional pattern that matches closing ) only if group #1 is not null i.e. ( is present on left of the match.
like image 50
anubhava Avatar answered Sep 29 '22 12:09

anubhava


Finally, it works:

^(\((\d{3})\)|(\d{3}))[\s\-\.]?\d{3}[\s\-\.]?\d{4}

tested in notepad++

like image 21
Michał M Avatar answered Sep 29 '22 11:09

Michał M