5

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)).

1 Answer 1

3

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\\-.].

Sign up to request clarification or add additional context in comments.

15 Comments

Thank you for your help @bohemian. Actually i forgot to mention that i didn't want to extract the country code, too. But this helps me a lot. If you can post me another regexp to extract the phone number without the country code, will be the best. And thanks for the remarks, too.
Ok, i change my code to work with the country codes. Only for the curiosity, can you provide the new regex to exclude the country codes? Thanks a lot!
I have to remark a problem, in the live demo you provided, all the strings were matched, but when i run the above provided script, the next strings doesn't match: (0490)260722 (0)442207724 +33 (0)442207724 Can you help me with this?
I can help with vountry cides, but what exactly do you mean by "exclude"? I will look into your new examples.
I have looked into your new examples you're having problems with. I tried them and they match for new: See live demo. Tell me more about how/what you're matching
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.