-1

How can I improve this regex to extract only numbers that contain "-" or no characters present between numbers inside string. For Example:

My phone number is 647-871-9067. tax year 2013. $9,846.22.

Should Extract [647-871-9067]

or

My phone number is 6478719067. tax year 2013. $9,846.22.

Should Extract [6478719067] only.

This is the regex I have written but it is extracting 2013 along with phone number

\b\s\(?([0-9-*)?]*)
ashhad
  • 163
  • 1
  • 7
  • 18
  • 1
    Possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Andrey May 09 '16 at 18:25
  • @Andrey please read my whole question again. My problem is different than what you have mentioned. – ashhad May 09 '16 at 19:26
  • This is exactly the same problem -- regex for a phone number. At first it seems simple, e.g. create a general regex + some additional corner cases. When one needs to recognize more and more different formats, it's better to use a well tested library, e.g. one from [Google](https://github.com/googlei18n/libphonenumber). To get the idea, check this regex for punctuation within the number: `-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F \u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E`. – Andrey May 09 '16 at 19:59
  • I m already using libphonenumber library. My question is about extracting phone number from a string that also contains other numbers, figures in one line. – ashhad May 09 '16 at 20:12

1 Answers1

0

Below code regular expression will fetch only the phone number irrespective of '-' in between the phone number.

var string1 = '647-871-9067. tax year 2013. $9,846.22',
string2 = '6478719067. tax year 2013. $9,846.22',
regx = /(\d{3}-?\d{3}-?\d{4})/g;

string1.match(regx)   // will return "647-871-9067"
string2.match(regx)   // will return "6478719067"
  • I cannot use limits. I have users who are from different countries and every individual insert phone number in a different way. – ashhad May 09 '16 at 17:02
  • 1
    @ashhad Well perhaps in some countries `2013` **is** a valid phone number. What is the rule you want to enforce for what is a phone number? –  May 09 '16 at 17:52