What Are Regular Expressions?
Regular expressions (regex) are patterns used to match character combinations in strings. They are supported in virtually every programming language and are invaluable for search, validation, and text processing. The syntax can look intimidating at first, but most real-world patterns use a small set of building blocks covered in this cheat sheet.
Basic Matchers
. Any character except newline
\d Digit (0-9)
\D Non-digit
\w Word character (a-z, A-Z, 0-9, _)
\W Non-word character
\s Whitespace (space, tab, newline)
\S Non-whitespace
Quantifiers
* Zero or more
+ One or more
? Zero or one (optional)
{3} Exactly 3
{2,5} Between 2 and 5
{3,} 3 or more
Anchors & Boundaries
^ Start of string
$ End of string
\b Word boundary
Character Classes
[abc] Match a, b, or c
[^abc] Match anything except a, b, c
[a-z] Match any lowercase letter
[0-9] Same as \d
Groups & Alternation
(abc) Capture group
(?:abc) Non-capturing group
a|b Match a or b
\1 Back-reference to group 1
Practical Examples
Here are patterns you will actually use:
// Email (simplified)
^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$
// URL
https?:\/\/[\w.-]+\.[a-z]{2,}(\/\S*)?
// ISO date (YYYY-MM-DD)
^\d{4}-\d{2}-\d{2}$
// Hex color
^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
// Strong password (8+ chars, upper, lower, digit, special)
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Lookaheads & Lookbehinds
(?=abc) Positive lookahead — followed by abc
(?!abc) Negative lookahead — NOT followed by abc
(?<=abc) Positive lookbehind — preceded by abc
(?<!abc) Negative lookbehind — NOT preceded by abc
Lookaheads are especially useful for password validation rules (as shown in the strong password pattern above) because they assert conditions without consuming characters.
Test Your Patterns
Reading about regex is useful, but the fastest way to learn is by experimenting. Open the Regex Tester, paste a pattern and some sample text, and watch matches highlight in real time. You can tweak the pattern, add flags like g (global) and i (case-insensitive), and see capture groups extracted instantly.