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.
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.
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 $
.
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.
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.
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.
This expression contains a single character class \d
, this will match a single character that is a digit from 0-9
.
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.