Reputation: 2481
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:
And a combinations of spaces, hyphens and no-spaces, like:
Now, I need two things:
Don't allow more than one separator between numbers. At the moment, the regex allows a poorly formatted string, e.g.:
Upvotes: 1
Views: 55
Reputation: 626748
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.
Upvotes: 1