Regex tutorial: matching an email

A great topic! Matching an email address using regular expressions (regex) can be a bit tricky, but don't worry, I'm here to guide you through it.

The Basics

Before we dive into the regex, let's cover some basic requirements for an email address:

  1. It must start with a local part (the part before the @ symbol).
  2. The local part can contain letters, numbers, dots (.), hyphens (-), and underscores (_).
  3. The local part must be followed by the @ symbol.
  4. The domain part (the part after the @ symbol) must contain at least one dot (.) and cannot be longer than 253 characters.
  5. The domain part can contain letters, numbers, dots (.), hyphens (-), and underscores (_).

The Regex Pattern

Here's a regex pattern that matches most common email addresses:

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

Let's break it down:

Example Matches

Here are some examples of email addresses that match this regex pattern:

Example Non-Matches

Here are some examples of email addresses that do not match this regex pattern:

Tips and Variations

I hope this tutorial has helped you understand how to match email addresses using regular expressions!