A Practical Introduction to Regular Expressions

regexjavascripttext

Regular expressions are a compact language for matching patterns in text. They look intimidating at first, but a handful of building blocks cover most real-world needs.

The building blocks

  • Literals match themselves, so the pattern cat matches the text "cat".
  • Character classes match one of several characters, such as [0-9] for a digit.
  • Quantifiers repeat the previous item, such as + for one or more and * for zero or more.
  • Anchors match position rather than text, such as ^ for the start and $ for the end.
  • Groups capture part of a match, such as (\d{4}) for a four-digit year.

A few useful patterns

  • Email-like address: [A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}
  • One or more digits: \d+
  • A YYYY-MM-DD date: \d{4}-\d{2}-\d{2}

Matching in common languages

JavaScript:

const re = /\d{4}-\d{2}-\d{2}/
console.log('2026-10-11'.match(re))

Python:

import re
print(re.search(r'\d{4}-\d{2}-\d{2}', '2026-10-11'))

PHP:

if (preg_match('/\d{4}-\d{2}-\d{2}/', '2026-10-11', $m)) {
    echo $m[0];
}

Common pitfalls

  • Forgetting to escape special characters when you mean them literally.
  • Greedy quantifiers matching more than you intended.
  • Using .* across lines when the dot does not match newlines by default.

Frequently asked questions

  • What are the g, i, m, s and u flags? They control global, case-insensitive, multiline, dotAll and unicode behavior.
  • Is my input sent anywhere? No. A good tester runs entirely in your browser.

Need to check a pattern against real text? Try the free Regex Tester — it highlights matches and capture groups live, locally.