Regular expressions look like line noise the first time you see them. But 90% of the regex you'll ever write uses only about ten pieces. Learn those and you're done.
The essentials
- `.` — any character except newline
- `\d` — a digit (0-9)
- `\w` — a word character (letters, digits, underscore)
- `\s` — whitespace
- `^` and `$` — start / end of line
- `*` `+` `?` — zero-or-more, one-or-more, optional
- `( )` — capture group
- `[ ]` — character class ("any of these")
Copy-paste patterns
- **Email (good enough):** `^[^\s@]+@[^\s@]+\.[^\s@]+$`
- **URL:** `https?:\/\/[^\s]+`
- **Phone digits only:** `\D` (replace with empty)
- **Whitespace collapse:** `\s+` (replace with single space)
- **Trailing whitespace:** `\s+$`
- **Hex color:** `#([0-9a-fA-F]{3}){1,2}\b`
Test before you ship
Never trust a regex you haven't run against real data. Open [Regex Tester](/tools/regex-tester), paste your pattern and sample text, and watch matches highlight live.
The one rule
If your regex is longer than 40 characters, split it into two. Future-you will thank you.