8 min read
How Regular Expressions Work
Learn the building blocks of regular expressions — character classes, quantifiers, anchors, and groups — with practical JavaScript examples.
A pattern is a small program
A regular expression describes a set of strings. The engine walks through your text trying to match the pattern at each position, backtracking when a branch fails.
Building blocks
Character classes match one character from a set: \d is a digit, \w a word character, [a-f] a range. Quantifiers repeat the previous item: * zero or more, + one or more, ? optional, {2,4} between two and four. Anchors match positions: ^ the start, $ the end, \b a word boundary.
Practical examples
Each pattern below can be pasted into the Regex Tester with sample text after a --- line.
/^\d{4}-\d{2}-\d{2}$/ ISO date such as 2026-10-06
/#[0-9a-f]{6}\b/gi six-digit hex colors
/(\w+)@(\w+\.\w+)/ a simple email with captured user and domain
/\bTODO:?\s*(.+)$/gm TODO comments and their textGroups and flags
Parentheses create capture groups, which you can reference in replacements as $1, $2. Use (?:...) when you need grouping without capturing. Flags change behaviour: g finds all matches, i ignores case, m makes ^ and $ match at line breaks, and s lets . match newlines.
Avoid catastrophic backtracking
Nested quantifiers such as (a+)+ can take exponential time on input that almost matches. Keep patterns specific and anchor them when you can, especially when validating user input.
