Kamal Sayah
Kamal Sayah

Reputation: 11

Optimize the Dutch telephone number RegEx pattern

This is my current RegEx:

^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9])((\s|\s?-\s?)?[0-9])([0-9])\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]$

These are my test results:

Everything seems ok, but there is one :-) string which needs to be matched (correct telephone number) but the RegEx doesn't match. This is the 0345-123456. Can anybody help me complete (or optimize) my RegEx so that all the above tests are ok?

Thanks for helping!

Upvotes: 0

Views: 564

Answers (1)

The fourth bird
The fourth bird

Reputation: 163477

There are optional whitespace chars in the pattern, but in the example data there are no whitespace chars.

You could write a pattern to match the specific listed formats, and for a match only you can omit the capture groups.

Note that 0345-123456 is 2 times in the list.

^(?:(?:(?:\+|00)31|0)(?:\d-?\d{8}|\d\d-\d{7})|0\d{3}-\d{6})$
  • ^ Start of string
  • (?: Non capture group
    • (?:(?:\+|00)31|0) Match either +31 or 0031 or 0
    • (?: Non capture group
      • \d-?\d{8} Match a digit, optional - and 8 digits
      • | Or
      • \d\d-\d{7} Match 2 digits - and 7 digits
    • ) Close non capture group
    • | Or
    • 0 Match a single zero
    • \d{3}-\d{6} Match 3 digits - 6 digits
  • ) Close the outer non capture group
  • $ End of string

Regex demo

Upvotes: 1

Related Questions