Regular expressions basics
The handful of regex constructs you actually use daily, with runnable examples and the mistakes that bite beginners.
The core atoms
| Pattern | Matches |
|---|---|
. | any single character (except newline) |
\d | a digit; \w a word char; \s whitespace |
^ / $ | start / end of string (or line with /m) |
[abc] | one of a, b, or c; [^0-9] negated |
a* / a+ | zero-or-more / one-or-more of a |
a? | optional (zero or one) |
a{2,4} | between 2 and 4 of a |
Groups and alternation
Parentheses (β¦) capture a part so you can extract or backreference it. The pipe | means 'or'. Escape special characters with a backslash when you mean the literal character.
const re = /(\d{4})-(\d{2})-(\d{2})/; // YYYY-MM-DD
const m = re.exec('2026-09-17');
console.log(m[1], m[2], m[3]); // 2026 09 17import re
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', '2026-09-17')
print(m.groups()) # ('2026', '09', '17')Mistakes that bite
- Forgetting to escape
.β it matches any char, soa.balso matchesaXb. Use\.for a literal dot. - Catastrophic backtracking: nested quantifiers like
(a+)+$on hostile input can hang. Prefer possessive/atomic patterns or a parser. - Using regex to parse HTML/JSON β use a real parser instead.
- Assuming
\wcovers Unicode letters β in many engines it is ASCII-only; use the Unicode flag.
β οΈ
Validate, don't trust. If a regex is used for security (e.g. path or email checks), confirm it actually rejects bad input β and prefer library validators where they exist.
FAQ
Should I use regex to parse HTML?
No. HTML is not regular; use an HTML parser (BeautifulSoup, DOMParser, jsdom). Regex only for quick, trusted text extraction.
How do I test a pattern?
Use a live tester (regex101, regexr) with your real sample inputs before shipping it.
Related
JSON basics URL encoding (percent-encoding)
Last refreshed 2026-09-17.