
Regular expressions — regex for short — are a tiny language for describing patterns in text. They look intimidating because they are dense, but you only need a dozen symbols to handle most real tasks: finding, validating, and replacing text. This is the practical subset I reach for, with patterns you can copy and adapt.
The core building blocks
| Symbol | Matches |
|---|---|
. | Any single character |
\d / \w / \s | A digit / word char / whitespace |
* / + / ? | Zero-or-more / one-or-more / optional |
{2,4} | Between 2 and 4 repetitions |
[abc] | Any one of a, b, c |
^ / $ | Start / end of the string |
() | A capturing group |
| | OR (this or that) |
Patterns you can actually use
A pragmatic email check (not RFC-perfect, but fine for a form): ^[\w.%+-]+@[\w.-]+\.[A-Za-z]{2,}$. A simple US phone number allowing dashes or spaces: ^\d{3}[-\s]?\d{3}[-\s]?\d{4}$. Strip extra spaces down to one: replace \s+ with a single space. Pull the domain out of a URL: capture https?://([^/]+) and read group 1.
The mistakes everyone makes first
Two traps catch beginners. First, greedy matching: .* grabs as much as possible, so <.*> on <a><b> matches the whole thing, not just <a>. Add a ? to make it lazy: <.*?>. Second, forgetting to escape special characters: a literal dot is \., not ., because a bare dot means “any character.” And a famous piece of wisdom worth remembering: do not try to validate complex HTML or email edge cases with regex alone — use a real parser or library for those.
Test before you ship
Never paste a regex straight into production. Free tools like regex101.com and regexr.com show, character by character, what your pattern matches and why, with a live explanation panel. I keep regex101 open whenever I write anything non-trivial; it turns a guessing game into a five-minute, verifiable task. In code, prefer named groups and comments (verbose mode) so the next person — often future you — can read it.
Frequently asked questions
Is regex the same in every language?
The core syntax is very similar across JavaScript, Python, PHP and others, but small features (like lookbehind or named groups) vary. Test in the language you will deploy in.
Should I validate email with regex?
A simple regex catches obvious typos, but the only truly reliable email validation is sending a confirmation message. Do not chase a 'perfect' email regex.
What does greedy vs lazy mean?
Greedy quantifiers (*, +) match as much as possible; adding ? makes them lazy, matching as little as possible. Use lazy matching to avoid over-capturing.
Where can I test a regex safely?
Use regex101.com or regexr.com — they highlight matches live and explain each token, so you catch mistakes before using the pattern in code.