Reputation: 2843
So far I have (\+\d{{0-9}}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}
which hits all my test cases except for one (number 6 should be invalid).
=> 1 VALID - 2437284712
=> 2 VALID - (723)728-2020
=> 3 VALID - 243 728 4712
=> 4 VALID - (900)8593019
=> 5 INVALID - 24372847
=> 6 VALID - (723)728-20201
=> 7 INVALID - 243 78 4712
=> 8 INVALID - (800)CITYLINE
How can I make this regex be invalid for test case #6 when it contains 11 digits?
Upvotes: 2
Views: 82
Reputation: 163477
Aside from using anchors to assert the start ^
and the end $
of the string, to make test case #6 pass you could match either 4 or 5 digits by extending the quantifier at the end with ?\d{4,5}$
to match 4 or 5 digits.
That would then also match 11 digits in a row if that is allowed.
^(\+\d{{0-9}}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4,5}$
Another option is to use an alternation |
to specifically match that exact pattern with 5 digits at the end to keep your original matches and add one extra pattern:
^(?:(\+\d{{0-9}}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}|\(\d{3}\)\d{3}-\d{5})$
Upvotes: 0