Regular expressions ("regex") have a reputation for being write-only: easy to type, impossible to read a week later. The reputation is half deserved. The syntax is dense, but there are only a few dozen pieces, and once you know them you can read most patterns left to right like a sentence. This guide builds those pieces up one at a time, with examples you can paste into our Regex Tester to watch them match. Every pattern and output shown here was run in JavaScript (Node.js) before publishing, and the sections on flavors note where Python and PCRE behave differently.

Key Takeaways
  • A regex is a pattern of literals, character classes, quantifiers, anchors, and groups. Learn those five and you can read most patterns.
  • For validation, anchor the pattern with ^ and $; otherwise "abc123" passes a "digits only" check.
  • Quantifiers are greedy by default; add ? for lazy, or better, use a negated class like [^>]+.
  • Nested quantifiers such as (a+)+ can cause catastrophic backtracking that freezes a program.
  • JavaScript, PCRE, and Python share the basics but differ in named-group syntax, lookbehind rules, Unicode handling, and atomic groups.
Advertisement

Your First Pattern

A regex describes a set of strings. The simplest pattern is plain text: /cat/ matches the letters c-a-t anywhere they appear. The power comes from special characters that stand for kinds of text. This pattern finds a phone-style number:

'Call 555-0142 today'.match(/\d{3}-\d{4}/)[0]; // '555-0142'

Read it left to right: \d is any digit, {3} means exactly three of the previous item, - is a literal hyphen, then four more digits. In JavaScript, the slashes delimit a regex literal, and anything after the closing slash is a flag.

The Building Blocks

Literals and escaping

Most characters match themselves. Fourteen don't, because they have special meaning: . ^ $ * + ? ( ) [ ] { } | \, plus / inside a JavaScript literal. To match one literally, put a backslash in front. Forgetting this is a classic bug, because . matches any character:

/3.14/.test('3x14'); // true (the dot matched 'x') /3\.14/.test('3x14'); // false (now only a real dot matches)

Character classes

Square brackets match one character from a set. [aeiou] matches a single vowel, [0-9A-F] one hex digit, and a caret at the start negates the set: [^0-9] is any character that isn't a digit. Common sets have shorthands:

TokenMatchesOpposite
\dA digit, 0–9 (ASCII only in JavaScript)\D
\wA "word" character: letters A–Z, a–z, digits, underscore\W
\sWhitespace: space, tab, newline, and others\S
.Any character except a line break (unless the s flag is on)—

Quantifiers

A quantifier says how many times the item before it may repeat: * (zero or more), + (one or more), ? (zero or one), {n} (exactly n), {n,} (n or more), and {n,m} (between n and m). The ? makes the "u" optional here:

['color', 'colour', 'colr'].map(s => /^colou?r$/.test(s)); // [true, true, false]

Anchors and word boundaries

Anchors match a position, not a character. ^ is the start of the input, $ the end, and \b a boundary between a word character and a non-word character. Anchors are what turn "contains" into "is":

/\d+/.test('abc123'); // true: it contains digits /^\d+$/.test('abc123'); // false: it isn't only digits 'cat concatenate category'.match(/\bcat\b/g); // ['cat'] (whole word only)

Alternation

The pipe | means "or," and it has the lowest precedence of anything in a regex. That surprises people: ^cat|dog$ means "starts with cat" or "ends with dog," not "is cat or dog." Group the alternatives to fix it:

/^cat|dog$/.test('hotdog'); // true (matched 'dog$' alone) /^(?:cat|dog)$/.test('hotdog'); // false /^(?:cat|dog)$/.test('dog'); // true

Flags

Flags change how the whole pattern behaves. In JavaScript they go after the closing slash (/pattern/gi) or as the second argument to new RegExp():

FlagNameEffect
gglobalFind all matches, not just the first
iignore case/cat/i matches "Cat" and "CAT"
mmultiline^ and $ match at every line start and end
sdotAll. also matches line breaks
uunicodeTreat the pattern as Unicode code points; enables \p{...}
vunicodeSetsA stricter, extended form of u with set operations
ystickyMatch only at exactly lastIndex
dindicesReport start and end positions of each group
const text = 'item one\nnot this\nitem two'; text.match(/^item \w+/g); // ['item one'] (^ = start of input only) text.match(/^item \w+/gm); // ['item one', 'item two'] (^ = start of each line) /a.b/.test('a\nb'); // false /a.b/s.test('a\nb'); // true

Groups, Captures, and Backreferences

Parentheses do two jobs: they group items so a quantifier or alternation applies to all of them, and they capture what matched so you can use it later.

const m = '2026-10-31'.match(/(\d{4})-(\d{2})-(\d{2})/); m[1], m[2], m[3]; // '2026', '10', '31' '2026-10-31'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1'); // '10/31/2026' // Named groups are easier to read '2026-10-31'.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/).groups; // { year: '2026', month: '10', day: '31' } '2026-10-31'.replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, '$<d>.$<m>.$<y>'); // '31.10.2026' // Non-capturing group: group without saving /^(?:https?|ftp):\/\//.test('ftp://example.net'); // true // Backreference: \1 repeats whatever group 1 matched 'This is is a test of the the regex'.match(/\b(\w+)\s+\1\b/gi); // ['is is', 'the the']

To loop over every match with its groups, use matchAll with the g flag:

[...'a1b22c333'.matchAll(/([a-z])(\d+)/g)].map(m => [m[1], m[2]]); // [['a', '1'], ['b', '22'], ['c', '333']]

Lookarounds: Conditions Without Consuming

A lookaround checks what comes before or after the current position without including it in the match. There are four:

SyntaxNameMeans
X(?=Y)LookaheadX, if followed by Y
X(?!Y)Negative lookaheadX, if not followed by Y
(?<=Y)XLookbehindX, if preceded by Y
(?<!Y)XNegative lookbehindX, if not preceded by Y
'width: 120px; margin: 8em; top: 4px'.match(/\d+(?=px)/g); // ['120', '4'] 'width: 120px; margin: 8em; top: 4px'.match(/\b\d+(?!\d|px)/g); // ['8'] 'Total: $42.50, tax 3.40'.match(/(?<=\$)\d+(?:\.\d{2})?/g); // ['42.50'] // Several lookaheads at the start = several independent rules const strong = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{12,}$/; ['Password1234', 'password1234', 'Pass1'].map(s => strong.test(s)); // [true, false, false]

In the second line, (?!\d|px) also rules out a following digit; without it, the engine would happily match "12" out of "120px," because "12" is followed by "0," not "px." Lookarounds are precise but easy to get subtly wrong, so test them against inputs that should fail, not only ones that should pass. (Composition rules like the password check above are only one part of strength; see What Makes a Password Strong.)

Greedy vs. Lazy Matching

Quantifiers grab as much as they can and then give back only what's needed for the rest of the pattern to match. That's usually what you want, until it isn't:

'<b>bold</b> and <i>it</i>'.match(/<.+>/)[0]; // '<b>bold</b> and <i>it</i>' (greedy: one huge match) '<b>bold</b> and <i>it</i>'.match(/<.+?>/g); // ['<b>', '</b>', '<i>', '</i>'] (lazy) '<b>bold</b>'.match(/<[^>]+>/g); // ['<b>', '</b>'] (negated class)

Adding ? after a quantifier (*?, +?, ??, {n,m}?) makes it lazy: it takes as little as possible. The third version is usually best. "One or more characters that aren't >" says exactly what you mean and gives the engine less to backtrack through. (For real HTML, use an HTML parser; regex is fine for quick searches, not for parsing nested markup.)

Common Pitfalls

Catastrophic backtracking

When a match fails, a backtracking engine tries every other way the pattern could have matched. With nested quantifiers over the same characters, the number of ways explodes. /^(a+)+$/ tested against "aaaa…a!" has to try every way of splitting the run of a's into groups before it can report failure, and that count roughly doubles with each extra "a". In our Node.js tests, every two extra characters multiplied the time by roughly four, and a 28-character input already took more than a second; a few more characters can lock up a page for minutes. The simple /^a+$/ fails on the same input almost instantly.

To avoid it: don't nest quantifiers over overlapping patterns ((a+)+, (\w+\s?)*, (.*,)*), prefer specific negated classes over .*, cap input length before matching untrusted text, and where your flavor supports them, use atomic groups or possessive quantifiers. Our Regex Tester warns about nested quantifiers for this reason.

Four smaller traps

// 1. A global regex remembers lastIndex between test() calls const re = /\d/g; re.test('a1'); re.test('a1'); re.test('a1'); // true, false, true // 2. In a string, the backslash must itself be escaped new RegExp('\\d+').test('42'); // true new RegExp('\d+').source; // 'd+' (the backslash vanished) // 3. $ is special in replacement strings 'price: 5'.replace(/\d+/, '$$5.00'); // 'price: $5.00' ($$ = literal $) 'price: 5'.replace(/\d+/, () => '$5.00'); // 'price: $5.00' (functions are literal) // 4. Without the u flag, an emoji counts as two characters /^.$/.test('😀'); // false /^.$/u.test('😀'); // true

Flavor Differences: JavaScript, PCRE, and Python

"Regex" isn't one language. The basics above work almost everywhere, but these differences trip people up when they move a pattern between tools. JavaScript behavior follows the MDN regex guide; Python follows the re module documentation; PCRE (used by PHP, nginx, and many other tools) follows the PCRE2 pattern docs.

FeatureJavaScriptPython rePCRE2
Named group(?<name>…)(?P<name>…)Both forms
Replacement reference$1, $<name>\1, \g<name>Set by the host language
LookbehindAny lengthFixed width onlyLimited (bounded) length
Atomic groups / possessive quantifiersNoYes (Python 3.11+)Yes
\d on Unicode digitsASCII 0–9 onlyAny Unicode digit (unless re.ASCII)ASCII by default
Inline flags like (?i)Scoped form (?i:…) in newer enginesYesYes
RecursionNoNoYes, (?R)

Python also has three different "match" calls that catch JavaScript developers out: re.match() anchors only at the start, re.search() looks anywhere, and re.fullmatch() requires the entire string to match, which is the behavior you usually want for validation.

Practical Recipes

// Collapse runs of whitespace ' lots of space '.trim().replace(/\s+/g, ' '); // 'lots of space' // Split on commas or semicolons with optional spaces 'a, b;c ,d'.split(/\s*[,;]\s*/); // ['a', 'b', 'c', 'd'] // Extract hashtags 'Loving #regex and #JavaScript_tips!'.match(/#\w+/g); // ['#regex', '#JavaScript_tips'] // Check YYYY-MM-DD format (format only: 2026-02-30 still passes) /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/.test('2026-10-31'); // true // Sanity-check an email address (not full validation) /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test('jo@example.com'); // true // Escape user input before building a regex from it 'a.b*c'.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 'a\\.b\\*c'

Notice the date and email comments. A regex checks shape; it can't tell you February has no 30th or that a mailbox exists. Pair it with real parsing or a confirmation step. If you work with timestamps in logs, Unix Time Explained includes a pattern for 10- and 13-digit values, and URL Encoding Explained covers the escaping you'll meet when patterns run against query strings.

Frequently Asked Questions

Why does my pattern only find the first match?

In JavaScript, match() and replace() stop after the first match unless the pattern has the g flag. Use /pattern/g, or replaceAll() with a global regex.

What's the difference between .* and .*??

.* is greedy and matches as much as possible before backing off; .*? is lazy and matches as little as possible. When you know the delimiter, a negated class such as [^"]* is usually clearer and faster than either.

Can a regex freeze my program?

Yes. Patterns with nested or overlapping quantifiers can take exponential time on inputs that almost match. Avoid nested quantifiers, limit input length, and test against long non-matching strings. On a server, this is a known denial-of-service risk.

Will a regex from Stack Overflow work in my language?

The basics will, but check named groups, lookbehind, Unicode classes, and replacement syntax against the table above. Testing in a tool that uses your target engine is the fastest way to find out. Our tester uses your browser's JavaScript engine.

Should I validate email addresses with a regex?

Only loosely. The full address grammar is complicated, and the only real test is sending a confirmation message. A simple pattern that requires one @ and a dot in the domain catches typos without rejecting valid addresses.