eveo
eveo

Reputation: 2843

Regex to select a phone number of 10 digits but be invalid if the string contains more than 10 digits?

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

enter image description here source: debuggex.com

How can I make this regex be invalid for test case #6 when it contains 11 digits?

Upvotes: 2

Views: 82

Answers (2)

The fourth bird
The fourth bird

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}$

Regex demo

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})$

Regex demo

Upvotes: 0

Emma
Emma

Reputation: 27743

You can simply add start and end anchors and solve the problem, yet I doubt that your expression might be what you might have in mind, since it would pass +0{{0-9}} 2437284712:

^(\+\d{{0-9}}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$

Demo

Upvotes: 1

Related Questions