Regular expressions basics

The handful of regex constructs you actually use daily, with runnable examples and the mistakes that bite beginners.

The core atoms

PatternMatches
.any single character (except newline)
\da 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 17
import re
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', '2026-09-17')
print(m.groups())  # ('2026', '09', '17')

Mistakes that bite

⚠️
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.

JSON basics URL encoding (percent-encoding)

Last refreshed 2026-09-17.