This regex tutorial will explain how to validate phone numbers. Applying this aspect of regex to forms is a great way to make sure users are giving you correct data.
\(?(\d{3})[-.)]\-?\.?\d{3}[-.]\d{4}
The above REGEX code allows the developer to find any American phone number as well as obscure the phone number to keep the user data private using Quantifiers, Character Classes, Bracket Expressions, Groups, and Lazy/Greedy Matching.
(?
looks for something accuring once or more. In this tutorial it looks to see if parentheses wrap the area code of the phone number.
{3}
looks for an occurrence exactly the amount of times denoted in curly braces. This is how the REGEX finds the groupings of numbers {3} {3} {4}
\d
This Character class finds any number 0-9. I use this to find numbers and chain {} to it finding groups of 3 and 4 numbers.
(?(\d{3})
Regex first captures the whole phone number as Group 0. The example code is then stored as Group 1.
The dev can then use this group to modify the phone number to secure the data by replacing characters with the code:
1$-XXX-XXXX
that will looks like (919)-XXX-XXXX
This method could also be applied to passwords.
[-.)]
Inside of Brackets all characters lose their special meaning unless the first character is ^
which then excludes the characters from possibility, acting as a NOT parameter.
In this example the code is looking for the possibility of 3 different characters -,)
The hyphen must come first otherwise it is misinterprettted and assumes you are searching a range i.e. [0-9].
(?
is a LAZY quantifier and only applies to the character to its immediate left.
{3}
{} typically a GREEDY quantifier, in this instance the quantifier is fixed. It looks for exactly what is in the curly braces, no more, no less.
I'm a professional musician and amatuer ultra-marathoner changing careers into Full-Stack development. If you like this tutorial I'll happily do more and see if I can make them funny at all.
https://github.com/nosremetnarg