Regular expressions - quick reference (Python re syntax; most engines are similar).
Characters
. any character except newline (re.S makes it match newline too)
\d \D digit / non-digit
\w \W word character [A-Za-z0-9_] / non-word
\s \S whitespace / non-whitespace
[abc] one of a, b, c [^abc] anything except a, b, c
[a-z0-9] ranges
Anchors
^ $ start / end of string (or of each line with re.M)
\b word boundary
Quantifiers
* + ? 0+, 1+, 0 or 1 (greedy)
{3} {2,5} exactly 3, between 2 and 5
*? +? ?? lazy versions: match as little as possible
Groups
(abc) capture group
(?:abc) group without capturing
(?P<year>\d{4}) named group -> m.group("year")
a|b alternation
(?=x) (?!x) lookahead / negative lookahead
(?<=x) (?<!x) lookbehind / negative lookbehind
Examples
^\d{4}-\d{2}-\d{2}$ ISO date such as 2024-03-15
^[\w.+-]+@[\w-]+(\.[\w-]+)+$ rough email check
^\s+|\s+$ leading or trailing whitespace
(\w+)\s+\1 doubled word ("the the")
^#[0-9a-fA-F]{6}$ hex colour
Python
import re
re.search(r"\d+", s) first match anywhere (or None)
re.fullmatch(r"\d+", s) whole string must match
re.findall(r"\d+", s) list of all matches
re.sub(r"\s+", " ", s) collapse whitespace
re.split(r"[,;]\s*", s) split on comma or semicolon
pat = re.compile(r"...", re.I) compile once, reuse; re.I = ignore case
Always use raw strings (r"...") so backslashes reach the regex engine unchanged.Or: /edit?page=RegexCheatsheet&text=your+text&name=YourName
Index | Recent changes | permalink | rev 06b81218e836