7

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?

Community
  • 1
  • 1
Gerard Nijboer
  • 502
  • 1
  • 7
  • 18

1 Answers1

8

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.

Andreas Neumann
  • 10,734
  • 1
  • 32
  • 52
  • That would also match 50 000 000 residents of a country, or a 240 15 12 sports record, you know. – jcolebrand Dec 05 '12 at 15:14
  • As stated above 240 15 12 and 50 000 000 may be valid phone numbers. If the number indicates a mere count or a telephone-number is just given by the context. For example +240 7 / 15 12 would be a valid telephone number in Equatorial Guinea. – Andreas Neumann Dec 08 '12 at 09:25
  • US/NANP numbers are XXX XXX-XXXX, or (XXX) XXX-XXXX. This expects a plus symbol to be in the country code, though if `?:` works, it will be optional. I've never gotten `?:` to work, myself - always had to use `?` after the group to make it optional. The "actual number" portion looks pretty broad and just seems to allow slashes (why?), digits, hyphens, periods, and spaces - no validation on a specific format, length, where spaces/hyphens go, etc. But I guess he got what he asked for, on that. – vapcguy Aug 15 '14 at 21:52
  • ?: doesn't mark a regex sequence as optional. The it just marks a group as non capturing. As the difference between how numbers are written down differs largely you either could get a lot false positives and filter later on as described here or do it beforehand. – Andreas Neumann Aug 18 '14 at 07:49