Regular expressions look like line noise until the pieces click — then they become one of the most useful tools you own. Here’s a beginner-friendly cheat sheet you can actually remember.
Character classes
.— any character (except newline, unless thesflag is set).\d— a digit;\D— a non-digit.\w— a word character (letter, digit, underscore);\W— the opposite.\s— whitespace;\S— non-whitespace.[abc]— any one of a, b, c.[a-z]— a range.[^abc]— anything except a, b, c.
Quantifiers (how many)
*— zero or more.+— one or more.?— zero or one (optional).{3}— exactly 3.{2,4}— 2 to 4.{2,}— 2 or more.- Add
?to make a quantifier lazy (match as few as possible):.+?.
Anchors and boundaries
^— start of string (or line withm).$— end.\b— a word boundary — great for whole-word matches like\bcat\b.
Groups and alternation
( … )— a capture group; the matched text is remembered as group 1, 2, …(?: … )— a group that does not capture (for structure only).a|b— matches a or b.
Flags
g— find all matches, not just the first.i— case-insensitive.m—^and$match per line.s— let.match newlines.
A few practical patterns
- Digits only:
^\d+$ - A simple date:
\d{4}-\d{2}-\d{2} - Words:
\b\w+\b - A rough email:
[^@\s]+@[^@\s]+\.[^@\s]+
(Real email validation is famously hard — a rough pattern like this is fine for a quick check, not for RFC-perfect validation.)
Tips that save hours
- Build incrementally. Start with a small piece and add to it, watching matches update.
- Escape special characters you mean literally:
\.,\?,\(. - Beware greedy
.*— it grabs as much as possible; use.*?or a more specific class when it overreaches. - Test against real data, including the edge cases you expect to fail.
The fastest way to learn is to see matches highlight as you type. Try patterns live in the free regex tester — it highlights every match and lists capture groups, all in your browser.