Customising a RegExp for international phone numbers

77 Views Asked by At

I have this regular expression that matches most phone numbers:

^((\+|00)[1-9]{1,3})?(\-| {0,1})?(([\d]{0,3})(\-| {0,1})?([\d]{5,11})){1}$

It is fine with phone numbers like:

  • +39123456789
  • +39-123-456789
  • +39 123 456789

And a combinations of spaces, hyphens and no-spaces, like:

  • +39 123456789
  • +39-123 456789

Now, I need two things:

  1. Allow the dot as separator too, like this:
    • +39.123.456789
    • +39 123.456789
    • +39-123.456789
  2. Don't allow more than one separator between numbers. At the moment, the regex allows a poorly formatted string, e.g.:

    • +39- 123456789
1

There are 1 best solutions below

1
On BEST ANSWER

Just fixing your regex, I can suggest the following regex:

^(?![^ .-]*[ .-]{2})((\+|00)[1-9]{1,3})?[ .-]?((\d{0,3})[ .-]?(\d{5,11}))$

Here is a demo

EXPLANATION:

  • ^ - Start of string
  • (?![^ .-]*[ .-]{2}) - Making sure there are no subsequent separators
  • ((\+|00)[1-9]{1,3})? - Prefix + or 00 and 1 or 3 digits from 1-9 range
  • [ .-]? - Optinal separator
  • ((\d{0,3})[ .-]?(\d{5,11})) - 0 to 3 digits followed by an optional separator and then 5 to 11 digits
  • $ - End of string.

In case you do not make use of the capturing groups here, just remove them or make non-capturing:

^(?![^ .-]*[ .-]{2})(?:(?:\+|00)[1-9]{1,3})?[ .-]?\d{0,3}[ .-]?\d{5,11}$

Following your logic, we can further optimize this pattern as

^(?:\+|00)[1-9]{1,3}[. -]?[0-9]{3}[. -]?[0-9]{5,11}$

It is an improved version suggested by @Falt4rm in the comment.