Regular Expressions for Beginners
3 min read · Published
Table of contents
A regular expression (regex) is a compact pattern for matching text. Use it to validate input, search and replace, extract data from logs or split strings. This guide teaches the JavaScript flavour, which is close to most others. Follow along in the Regex Tester.
Literal matching
The simplest regex is just text: cat matches "cat" inside "concatenate". Most characters match themselves. Special characters (. * + ? ^ $ { } ( ) | [ ] \) must be escaped with a backslash to match literally: \. matches a real dot.
Character classes
| Pattern | Matches |
|---|---|
. |
any character except newline |
\d / \D |
a digit / a non-digit |
\w / \W |
a word character [A-Za-z0-9_] / its opposite |
\s / \S |
whitespace / non-whitespace |
[abc] |
a, b or c |
[a-z] |
any lowercase letter |
[^0-9] |
anything except a digit |
Quantifiers
| Pattern | Meaning |
|---|---|
* |
0 or more |
+ |
1 or more |
? |
0 or 1 |
{3} |
exactly 3 |
{2,5} |
between 2 and 5 |
{2,} |
2 or more |
\d{3}-\d{4} matches 555-1234. Quantifiers are greedy by default: <.+> on <b>x</b> matches the whole string. Add ? to make them lazy: <.+?> matches <b> then </b>.
Anchors and boundaries
^start of the string (or line with themflag)$end of the string (or line)\bword boundary:\bcat\bmatches "cat" but not "concatenate"
^\d+$ checks that the entire string is digits; without anchors a pattern matches anywhere.
Groups and alternation
(ab)+ one or more repetitions of "ab"
cat|dog either word
(?:ab)+ non-capturing group
(?<year>\d{4}) named capture group
Capturing groups let you extract parts of a match:
const m = '2026-11-15'.match(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/);
m.groups.y; // "2026"
Lookarounds
Lookarounds assert context without consuming characters:
| Pattern | Meaning |
|---|---|
foo(?=bar) |
"foo" followed by "bar" |
foo(?!bar) |
"foo" not followed by "bar" |
(?<=\$)\d+ |
digits preceded by $ |
(?<!\$)\b\d+ |
digits not preceded by $ |
Flags
| Flag | Effect |
|---|---|
g |
find all matches |
i |
ignore case |
m |
^ and $ match at line breaks |
s |
. also matches newline |
u |
full Unicode support (emoji, \p{L}) |
Using regex in JavaScript
const re = /\b\w+@\w+\.com\b/g;
'a@x.com, b@y.com'.match(re); // ['a@x.com', 'b@y.com']
re.test('hello'); // false
'2026-11-15'.replace(/-/g, '/'); // '2026/11/15'
'a1b22'.replace(/\d+/g, (n) => `<${n}>`); // 'a<1>b<22>'
[...'a1b22'.matchAll(/\d+/g)].map((m) => m[0]); // ['1', '22']
Combine with array helpers from JavaScript Array Methods for powerful one-liners.
Practical patterns
Date (YYYY-MM-DD) \d{4}-\d{2}-\d{2}
Hex colour #(?:[0-9a-fA-F]{3}){1,2}\b
Whitespace trimming ^\s+|\s+$
Duplicate words \b(\w+)\s+\1\b
Simple email check [^\s@]+@[^\s@]+\.[^\s@]+
The email pattern is only a sanity check. Real validation means sending a confirmation message.
Pitfalls
- Forgetting anchors in validation:
\d+accepts "abc123". - Escaping: in a JavaScript string you need
"\\d+"; use a regex literal/\d+/orString.rawto avoid doubling. - Catastrophic backtracking: nested quantifiers like
(a+)+$can take exponential time on certain inputs. Avoid ambiguity and limit input length, especially for user-supplied text on a server. - Parsing HTML or JSON with regex: use a real parser. Regex cannot handle arbitrary nesting.
gflag with.test()keepslastIndexbetween calls, a classic source of intermittent bugs.
Learning workflow
- Write a sample of text you want to match, including cases that must not match.
- Build the pattern step by step in the Regex Tester, watching matches highlight.
- Add anchors and flags last.
- Test edge cases: empty string, Unicode, very long input.
Tools that pair well with regex work: the Case Converter and the Text Diff Checker; and if you use git grep -E, see Git Commands Every Developer Should Know.
Related tools
Regex Tester
Test JavaScript regular expressions with live match highlighting.
Case Converter
Convert text to camelCase, snake_case, kebab-case and more.
Text Diff Checker
Compare two texts and see added and removed lines.
FAQ
What does the g flag do?
It finds all matches instead of stopping at the first.
Greedy vs lazy quantifiers?
Greedy quantifiers (*, +) match as much as possible; adding ? (*?, +?) makes them match as little as possible.
Should I validate emails with regex?
Use a simple sanity check, then confirm by sending a verification email. A fully RFC-compliant regex is impractical.
Keep reading
- JavaScript Array Methods: A Practical Guide
A practical tour of the JavaScript array methods you will use daily: map, filter, reduce, find, some, every, flat, sort and more, with examples.
- Git Commands Every Developer Should Know
The essential Git commands for daily work: staging, committing, branching, merging, rebasing, stashing and undoing mistakes safely.