Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best regular expression for phone numbers? [duplicate]

Possible Duplicate:
A comprehensive regex for phone number validation
What regular expression will match valid international phone numbers?

I've seen some posts on StackOverflow on regular expressions that match phone numbers. But many don't seem to take into account possible spaces or dashed between numbers to increase readability.

I'm from the Netherlands, but I'd like to use a regex which matches any phone number, including those in foreign countries.

I'd like to use it for a plugin such as the Skype find-and-replace plugin for browsers.

Currently, I'm using the following regex:

^((\+)?)([\s-.\(\)]*\d{1}){8,13}$

Has anybody got any improvements for that one?

like image 408
Gerard Nijboer Avatar asked Dec 05 '12 08:12

Gerard Nijboer


1 Answers

I'd go with

# countryCode
(?:\+\d{1,3}|0\d{1,3}|00\d{1,2})

# actual number
(?:[-\/\s.]|\d)+

# combined with optional country code and parantheses in between
 ^(?:\+\d{1,3}|0\d{1,3}|00\d{1,2})?(?:\s?\(\d+\))?(?:[-\/\s.]|\d)+$

This should be good enough to match most most European and US representations of a phone Number as

+49 123 999
0001 123.456
+31 (0) 8123

But in general there are too many overlapping textual representation of a phone Number as to use a single Regex for different countries. If you could match all representations you'll get to many false positives. As what may be a number in Switzerland may be something else in Russia, Germany or Ghana. It's all about balancing precission and recall and optimizing the Regex to the countries you really need.

like image 63
Andreas Neumann Avatar answered Sep 18 '22 00:09

Andreas Neumann