Skip to content

Instantly share code, notes, and snippets.

@kcmuse
Last active August 16, 2021 23:04
Show Gist options
  • Save kcmuse/d111458c3c2a7d40a8662b9bf39116e9 to your computer and use it in GitHub Desktop.
Save kcmuse/d111458c3c2a7d40a8662b9bf39116e9 to your computer and use it in GitHub Desktop.
Regex Tutorial - Email matching

Regex Tutorial

This is a tutorial explaining the use of a regex to match emails using the following expression

/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/

This regex is used when validating emails used in an application that uses MongoDB or Node.

Summary

A regex or more officially refered to as a regular expression is a sequence of characters that define a search pattern. These are commonly used to determin patterns within a string. This tutorial will walk through the uses of this regex, and how its used to determine if an email is in fact a valid email.

Table of Contents

Regex Components

Anchors

The anchors used in this regex for matching emails are ^, this here defines the beggining of a string, to identify the end of the expression we use $.

Quantifiers

There are two quantifiers within this regex, the first being + which is a greedy quantifier. This quantifier will allow connection for the users email+ email service + .com. The other quantifier is the {2,6}, this will match everything after the . 2-6 times to ensure it has at least 2 characters and no more than 6.

Grouping Constructs

Each grouping construct is capturing pieces of data. The first group ([a-z0-9_\.-]+) will capture the email name, the second group ([\da-z\.-]+) will capture the users email provider and lastly the ([a-z\.]{2,6}) will capture the top level domain imput from the user.

Bracket Expressions

Bracketed expressions within the email validation are within the []. In the first part of the regex ([a-z0-9_\.-]+) everything within the [] is going to match any letter a-z, any number from 0-9 and the characters _, .,-. This regex has 3 sets of bracketed expressions each looking for different pieces of information.

Character Classes

This expression contains a single character class \d, this will match a single character that is a digit from 0-9.

Character Escapes

This regex does have use for the character escapes, within all of the groups each contains \.. Adding the \ in front of the . will "escape" the ., making it literal instead of a special character.

Author

All of my work is viewable from my Github !

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