The Complete Guide to Regular Expressions
Regular expressions are a tiny language for describing text patterns. They power search-and-replace, validation, and parsing in nearly every language and editor — and they're famously cryptic. This guide builds them up piece by piece so the symbols stop looking like line noise.
Prefer a focused read? Jump to Character Classes, Quantifiers & Anchors for the building blocks, or Groups, Backreferences & Lookarounds for the advanced features.
What a regex is
A regular expression is a pattern matched against text. The simplest patterns are literals — cat matches the letters c-a-t anywhere in the input. The power comes from metacharacters, symbols that mean "a kind of character" or "a repetition" rather than themselves.
In most languages a pattern is written between slashes with optional flags: /pattern/flags. In JavaScript, /cat/i matches "cat" case-insensitively.
Metacharacters and escaping
A handful of characters are special: . ^ $ * + ? ( ) [ ] { } | \. To match one literally, escape it with a backslash — \. matches a real dot, \$ a real dollar sign. The most useful metacharacter is ., which matches any single character (except a newline, by default).
Character classes
A character class in square brackets matches one character from a set:
[aeiou]— any one vowel[a-z]— any lowercase letter (a range)[^0-9]— any character that is not a digit (a negated class)
Common sets have shorthands: \d (digit), \w (word character), \s (whitespace), and their negations \D, \W, \S. Full details in Character Classes, Quantifiers & Anchors.
Quantifiers
Quantifiers say how many times the preceding item may repeat:
*— zero or more ·+— one or more ·?— zero or one{3}— exactly 3 ·{2,4}— 2 to 4 ·{2,}— 2 or more
By default quantifiers are greedy (they match as much as possible); adding ? makes them lazy (as little as possible). So \d+ grabs a whole number, while \d+? grabs one digit at a time.
Anchors and boundaries
Anchors match a position, not a character: ^ is the start of the string (or line), $ is the end, and \b is a word boundary. ^\d+$ means "the entire string is digits"; \bcat\b matches "cat" as a whole word but not inside "category".
Groups, alternation, and flags
Parentheses group part of a pattern and capture what it matched: (\d{4}) captures a four-digit year. A pipe means alternation (or): cat|dog matches either. For capturing, backreferences, and lookarounds, see Groups, Backreferences & Lookarounds.
Flags change how the whole pattern behaves — g (find all matches), i (ignore case), m (^/$ match per line), s (let . match newlines).
Related
Build a pattern incrementally and watch it match with the Regex Tester, and keep the Regex Cheat Sheet handy — all in your browser.
Try it
Type a pattern and paste real text to see matches highlight live as you go — nothing is uploaded.