Skip to content

Instantly share code, notes, and snippets.

@nosremetnarg
Last active September 26, 2020 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nosremetnarg/7fd2bd34508f59b580fb089109ece5c3 to your computer and use it in GitHub Desktop.
Save nosremetnarg/7fd2bd34508f59b580fb089109ece5c3 to your computer and use it in GitHub Desktop.
REGEX Tutorial - Validating Phone Numbers

REGEX Tutorial - Phone Number Validation

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}

Summary

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.

Table of Contents

Regex Components

Quantifiers

(? 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}

Character Classes

\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.

Grouping and Capturing

(?(\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.

Bracket Expressions

[-.)] 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].

Greedy and Lazy Match

(?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.

Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment