简体   繁体   中英

Javascript RegExp - extract phone numbers from string

I have the following working regex to extract a lot of phone numbers in different formats.

See here: http://jsfiddle.net/SB5Ly/4/

var regex = new RegExp(
            "\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+",
            "g"
        );
....

(If the script didn't load, press the "Run" button from the top menu)

As you can see in the example (by following the link), the last 2-3 phone number formats (var phoneNumbers) doesn't match the used regex. You can test the regex modifying it in the script and running it.

So i need a regex that match all the enumerated phone number formats (to extract them from an entire webpage (document.body.innerHTML)).

I don't know how prescriptive you want to be, but this matches all your examples:

var regex = new RegExp("\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+", "g");

See a live demo of this regex.


One small bug with your regex: When wanting to include a literal dash in a character class, either escape it or place it first or last.

You had [\\\\s-.] , which is incorrect. It should be either [\\\\s.-] , [-\\\\s.] or [\\\\s\\\\-.] .

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