Regular expression validating phone number
Validating a phone number using regular expression is tricky because the phone number can be written in many formats and can have extensions also.
, composing a fairly comprehensive guide to validating and formatting North American and international phone numbers using regular expressions. Thus, the sequences that enclose the first group of digits match literal parenthesis characters.
Those numbers are guaranteed not to connect to an actual phone number so they're often used in television and movies to ensure that a viewer doesn't try to call the number and end up harassing some poor [email protected] While that was true decades ago, it is no longer true. Honestly, I would recommend you don't try to validate phone numbers.
The 555 prefix is still special, but only a small range of numbers are guaranteed to terminate without connection 555-0100 to 555-0199. This is good and all, but it doesn't validate what was entered was actually a phone number. Even if you could write a big, hairy validator that would allow all the different legitimate formats, it would end up allowing pretty much anything even remotely resembling a phone number in the first place.
The regexes in these recipes are all pretty straightforward, but hopefully this gives an example of the depth you can expect from the book. Both are followed by a question mark, which makes them optional.
Below are a few phone numbers that you might encounter when using real data, write a single regular expressions that matches the number and captures the proper area code.
\d part checks for zero or one occurrence of a digit.
So here I think the second question mark right before the digt is checking for digit and not the parenthesis.
If you are ready to plug and play, be our guest: the practical regular expressions are listed and described in Chapters 4 through 9.
But the initial chapters of this book may save you a lot of time in the long run.