BeniaminoBaggins
BeniaminoBaggins

Reputation: 12433

Regex - Phone numbers or empty space not working

I have this regex for phone numbers in New Zealand:

^\+?[\d\s\(\)]{1,14}$|^((\+?64\s*[\(]?2\d{1}[\)]?|\(?02\d{1}\)?)\s*\d{3}\s*\d{3,5})$

enter image description here

I want to allow an empty string as well so I do what the internet says to do (add ^$| to the front):

enter image description here

As you can see it makes most of the passing numbers fail. It does the same thing when I add brackets to the front.

How do I allow empty strings and also phone numbers using the expression at the top of this question?

Please copy paste this into regexr.com to experiment with possible solutions:

expression:

^\+?[\d\s\(\)]{1,14}$|^((\+?64\s*[\(]?2\d{1}[\)]?|\(?02\d{1}\)?)\s*\d{3}\s*\d{3,5})$

Text:

Positive:
021 755 2375

+79261234567
9261234567
+1234567
89261234567
4035555678
23423
3454
021 2343234
926 3 4
1 416 555 9292
926 1234567
495 1234567
+7 555 1234567
+7(926)1234567
(926) 1234567
469 123 45 67
0800 345345786
09 419 7555
0800 475 4669
202 555 4567

Negative:

027 .343 -454
8 800 600-APPLE
+42 555.123.4567
926.123.4567
64 25 .435 -34323
025 .435                        -343
123-4567
123-89-01
+1-(800)-123-4567
8 (926) 1234567
415-555-1234
650-555-2345
(416)555-3456
09-419 7555
364563456345645643565346768

Upvotes: 0

Views: 82

Answers (1)

dawg
dawg

Reputation: 103774

Use grouping:

(?:^$)|(?:^\+?[\d\s\(\)]{1,14}$|^((\+?64\s*[\(]?2\d{1}[\)]?|\(?02\d{1}\)?)\s*\d{3}\s*\d{3,5})$)

Demo

Upvotes: 1

Related Questions