简体   繁体   中英

Extract Phone number only when other numbers are present in a string

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-*)?]*)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM