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:
- Allow the dot as separator too, like this:
- +39.123.456789
- +39 123.456789
- +39-123.456789
Don't allow more than one separator between numbers. At the moment, the regex allows a poorly formatted string, e.g.:
- +39- 123456789
Just fixing your regex, I can suggest the following regex:
Here is a demo
EXPLANATION:
^
- Start of string(?![^ .-]*[ .-]{2})
- Making sure there are no subsequent separators((\+|00)[1-9]{1,3})?
- Prefix+
or00
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:
Following your logic, we can further optimize this pattern as
It is an improved version suggested by @Falt4rm in the comment.