Back to roadmaps regex Course

Validating Emails and URLs with Regex

Email and URL validation are two of the most common real-world regex applications. Let us deconstruct classic validation patterns.


1. Email Address Validation

A practical email validation regex checks for the most common valid formats without attempting to cover all edge cases:

// Practical email validator
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

emailRegex.test("user@example.com");    // true
emailRegex.test("user.name+tag@sub.example.co.uk"); // true
emailRegex.test("user@.com");           // false (domain starts with dot)
emailRegex.test("@example.com");        // false (no local part)

Pattern breakdown:

  • ^[a-zA-Z0-9._%+-]+: Local part (letters, digits, dots, underscores, percent, plus, hyphen — one or more)
  • @: The at-sign separator
  • [a-zA-Z0-9.-]+: Domain name (letters, digits, dots, hyphens)
  • \.[a-zA-Z]{2,}$: Top-level domain with at least 2 letters

2. URL Validation and Parsing

To validate a URL and extract its components using named groups:

const urlRegex = /^(?<protocol>https?):\/\/(?<hostname>[\w.-]+)(?<path>\/[^\s]*)?$/;

const match = "https://api.example.com/v1/users?page=2".match(urlRegex);
if (match) {
  console.log(match.groups.protocol); // "https"
  console.log(match.groups.hostname); // "api.example.com"
  console.log(match.groups.path);     // "/v1/users?page=2"
}
Published on Last updated: