Regex Basics: A Practical Guide
- The building blocks
- Character classes: what to match
- Quantifiers: how many
- Anchors: where
- Groups and alternation
- Three worked examples
- 1. Digits only
- 2. An email-shaped pattern
- 3. Extracting a substring with a capture group
- The pitfalls that cause real bugs
- Greedy versus lazy matching
- Forgetting to escape
- When not to use regex
- Frequently asked questions
- What do the g, i and m flags do?
- Is regex syntax the same in every language?
- Why does my pattern work in a tester but not in my code?
On this page
- The building blocks
- Character classes: what to match
- Quantifiers: how many
- Anchors: where
- Groups and alternation
- Three worked examples
- 1. Digits only
- 2. An email-shaped pattern
- 3. Extracting a substring with a capture group
- The pitfalls that cause real bugs
- Greedy versus lazy matching
- Forgetting to escape
- When not to use regex
- Frequently asked questions
- What do the g, i and m flags do?
- Is regex syntax the same in every language?
- Why does my pattern work in a tester but not in my code?
A regular expression is a compact language for describing patterns in text. Instead of writing a loop that inspects each character, you write a short string meaning "one or more digits, then a dash, then exactly four letters" and hand it to an engine that does the scanning. Every mainstream language ships one, and the syntax is close enough between them that what you learn in JavaScript carries over to Python, Go or grep.
Regex has a reputation for being write-only: easy to produce, painful to read back six months later. Most of that pain comes from a handful of specific misunderstandings rather than the syntax being hard. This guide covers the pieces you'll use constantly, three worked examples, and the mistakes that produce patterns which look right and silently aren't.
The building blocks
Almost every useful pattern is assembled from four kinds of piece: what to match, how many times, where, and how to group the result.
Character classes: what to match
Square brackets define a set of characters, any one of which matches at that position. [abc] matches a single a, b or c. A hyphen denotes a range, so [a-z] is any lowercase letter. A caret at the start negates the set: [^0-9] matches any character that isn't a digit.
- \d — any digit, equivalent to [0-9].
- \w — any word character: letters, digits and underscore ([A-Za-z0-9_]).
- \s — any whitespace: space, tab, newline.
- \D, \W, \S — the negated versions of the three above.
- . — any character at all, except a newline by default.
Quantifiers: how many
A quantifier applies to whatever came immediately before it — a character, a class, or a group. The four you'll use constantly are * (zero or more), + (one or more), ? (optional), and {n,m} (between n and m times). {3} means exactly three; {2,} means two or more.
Anchors: where
^ matches the start of the string and $ the end. These match positions, not characters — they consume nothing. Without them a pattern is free to match anywhere inside a longer string, which is what you want when searching and definitely not what you want when validating. \b marks a word boundary, so \bcat\b matches "cat" in "the cat sat" but not inside "concatenate".
Groups and alternation
Parentheses group part of a pattern so a quantifier applies to the whole thing, and they capture whatever matched so you can extract it. (ab)+ matches "ababab"; without them, ab+ matches "abbb". The pipe | means alternation, and it has very low precedence, so wrap it in a group: ^(cat|dog)$ rather than ^cat|dog$, which actually means "starts with cat, or ends with dog". For grouping without capturing, use (?:...).
Three worked examples
Here are three patterns you'd plausibly write in real work, broken down.
1. Digits only
You want to confirm a field contains nothing but digits — an OTP, a PIN, a numeric ID. The pattern is ^\d+$, and the anchors do the real work:
- ^ — anchor to the start of the string.
- \d+ — one or more digits.
- $ — anchor to the end of the string.
- Without the anchors, \d+ alone would match the "42" inside "abc42def" and pass a check it should fail.
- For a fixed-length code, swap + for an exact count: ^\d{6}$ for a six-digit OTP.
2. An email-shaped pattern
A pragmatic pattern for catching obvious typos is ^[^\s@]+@[^\s@]+\.[^\s@]+$ — "characters that aren't spaces or at-signs, an at-sign, more of the same, a literal dot, more of the same". Note the \. in the middle: an unescaped dot matches any character, so "user@examplecom" would wrongly pass.
This deliberately isn't a full RFC 5322 validator. The complete grammar permits quoted strings and comments, and the canonical regex for it runs to thousands of characters. A loose pattern to catch typos, followed by an actual confirmation email, is both simpler and more correct than any regex claiming to prove an address exists.
3. Extracting a substring with a capture group
Say you're pulling version numbers out of log lines like "build v2.14.3 completed". The pattern v(\d+\.\d+\.\d+) matches the literal v, then captures three dot-separated number groups. The full match is "v2.14.3", but capture group 1 holds just "2.14.3" — the part you actually want.
- v — a literal character to anchor the match somewhere meaningful.
- \d+\.\d+\.\d+ — three groups of digits separated by escaped literal dots.
- ( ... ) — the parentheses capture that span as group 1 in the match result.
- Add the g flag to find every version in a multi-line log rather than only the first.
The pitfalls that cause real bugs
Greedy versus lazy matching
Quantifiers are greedy by default: they consume as much as they can while still letting the rest of the pattern match. Run <.+> against "<a><b>" and you get one match spanning the whole string, not two — because .+ grabs everything and backtracks only enough to let the final > match.
Appending a ? makes a quantifier lazy, so it consumes as little as possible: <.+?> on the same input yields two matches, "<a>" and "<b>". The same applies to *? and {n,m}?. When a pattern matches far more text than expected, greediness is the first thing to check.
Forgetting to escape
A dozen or so characters have special meaning in regex — . * + ? ^ $ ( ) [ ] { } | \ — and matching one literally means prefixing it with a backslash. The unescaped dot is the classic offender, because a bare dot usually still appears to work: it matches the dot you intended and also every other character, so the bug only surfaces on input you didn't test.
Watch out
If any part of your pattern comes from user input, escape it before interpolating. An unescaped string can silently change the pattern's meaning, or cause catastrophic backtracking — nested quantifiers like (a+)+$ take exponential time on a crafted input and hang the process. That's a real denial-of-service class known as ReDoS.
When not to use regex
A regex checks shape, not truth: ^\d{2}/\d{2}/\d{4}$ confirms something looks like a date but accepts 99/99/9999. More fundamentally, regular expressions describe regular languages — a mathematical limitation, not a style preference. Anything with arbitrarily nested structure is beyond what regex can correctly express, and the near-misses are worse than outright failure because they work on your test data.
- HTML and XML: nesting is unbounded, and attributes, comments and self-closing tags break naive patterns. Use a parser.
- JSON: same reason — objects and arrays nest arbitrarily deep. Every language ships a JSON parser.
- Source code: matching balanced brackets or quotes is a known dead end. Use an AST tool.
- CSV with quoted fields: a field can contain commas and escaped quotes, so splitting by pattern corrupts rows.
Tip
Build patterns incrementally in a tester rather than writing the whole thing and debugging the result. Start with the simplest piece that matches, confirm it against real sample data including cases that should fail, then add one element at a time. Most regex bugs come from writing forty characters before testing any of them.
Frequently asked questions
What do the g, i and m flags do?
The g (global) flag finds every match rather than stopping at the first, which matters for replace operations and match loops. The i flag makes matching case-insensitive. The m (multiline) flag makes ^ and $ match at the start and end of each line rather than the whole string — useful for log files, and a common surprise for anyone expecting that by default.
Is regex syntax the same in every language?
The core — classes, quantifiers, anchors, groups, alternation — is effectively universal. Differences appear in the advanced corners: lookbehind support, named group syntax, Unicode property escapes and how the multiline flag is spelled. A pattern using only the basics ports unchanged; one using lookbehind may not.
Why does my pattern work in a tester but not in my code?
Usually escaping. When a pattern is written as a string rather than a literal, the language's string parser eats one level of backslashes first, so \d must be written \\d. The other frequent cause is a stateful global regex in JavaScript: a /g pattern held in a variable carries a lastIndex between test() calls, so repeated calls seem to alternate between matching and not.
Regex rewards a small vocabulary used carefully far more than cleverness. Learn the classes, the four quantifiers, the anchors and grouping; anchor your validation patterns; escape your literals; reach for a parser when structure nests. That covers most real work and leaves patterns you can still read months later.
Ready to put this into practice?
Test Your Regex Free