All Cheat Sheets
Regex Cheat Sheet
Regex cheat sheet for regular expressions: character classes, quantifiers, anchors, groups, lookarounds, flags, Python re module, Java/PHP/grep differences and common patterns.
Character Classes
.Any character except newlineDigit
\dDigit [0-9]Non-digit
\DNon-digitWord
\wWord char [a-zA-Z0-9_]Non-word
\WNon-word charSpace
\sWhitespaceNon-space
\SNon-whitespaceSet
[abc]Any of a, b, or cNegated set
[^abc]Not a, b, or cRange
[a-z]Range a to zQuantifiers
Star
*0 or morePlus
+1 or moreOptional
?0 or 1Exact
{n}Exactly nMin
{n,}n or moreRange
{n,m}Between n and mLazy star
*?0 or more (lazy)Lazy plus
+?1 or more (lazy)Anchors & Boundaries
Start
^Start of stringEnd
$End of stringBoundary
\bWord boundaryNon-boundary
\BNon-word boundaryGroups & References
Group
(abc)Capture groupNon-capture
(?:abc)Non-capture groupNamed
(?<name>abc)Named groupBack-ref
\1Back-referenceOr
a|bAlternation (OR)Lookaheads & Lookbehinds
Lookahead
(?=abc)Positive lookaheadNeg lookahead
(?!abc)Negative lookaheadLookbehind
(?<=abc)Positive lookbehindNeg lookbehind
(?<!abc)Negative lookbehindCommon Patterns
Email
[\w.-]+@[\w.-]+\.\w+URL
https?://[\w.-]+(?:/[\w./-]*)?IPv4
\d{1,3}(\.\d{1,3}){3}Hex color
#[0-9a-fA-F]{3,8}Phone (US)
\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}Flags & Modifiers
Case-insensitive
/abc/i (?i)abci flag in JS/PCRE; inline (?i) in Python, Java, PCRE, .NETGlobal (JS)
/\d+/gFind all matches with matchAll/replace; other languages use findall/replaceAll insteadMultiline
/^\w+/m (?m)^ and $ match at every line start/end, not just the stringDot matches newline
/a.b/s (?s)Called DOTALL in Python and JavaVerbose / extended
(?x) \d{4} - \d{2} # commentWhitespace ignored, # starts a comment (Python, PCRE, Java)Unicode (JS)
/\p{L}+/u /[\p{L}--\p{Ll}]/vu enables \p{...}; v (ES2024) adds set operationsSticky (JS)
/foo/yMatch only at lastIndexPython re Module
Raw strings
import re
pattern = r"\d+\.\d+"r"..." stops Python from interpreting backslashes before re sees themsearch (anywhere)
m = re.search(r"\d+", "order 42")
m.group() # '42'Returns a Match or Nonematch (at start)
re.match(r"\d+", "42 apples") # match
re.match(r"\d+", "x42") # Nonefullmatch (whole string)
re.fullmatch(r"[a-z0-9-]+", slug)Best for validation; no need for ^...$findall
re.findall(r"\d+", "a1 b22 c333") # ['1', '22', '333']With groups it returns the groups (tuples if several)finditer
for m in re.finditer(r"\w+@\w+\.com", text):
print(m.group(), m.span())sub (replace)
re.sub(r"\s+", " ", text)
re.sub(r"(\w+)@(\w+)", r"\2 at \1", s)sub with function
re.sub(r"\d+", lambda m: str(int(m.group()) * 2), s)split
re.split(r"[,;]\s*", "a, b;c") # ['a', 'b', 'c']Named groups
m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", s)
m.group("year")
m.groupdict()Python syntax is (?P<name>...); backreference with (?P=name)Named group in sub
re.sub(r"(?P<y>\d{4})-(?P<m>\d{2})", r"\g<m>/\g<y>", s)Flags
re.search(r"^error", log, re.I | re.M)re.I ignorecase, re.M multiline, re.S dotall, re.X verboseCompile & reuse
DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
DATE.findall(text)Escape user input
re.escape("1+1=2?") # '1\\+1=2\\?'Version notesAtomic groups (?>...) and possessive quantifiers (*+, ++) need Python 3.11+; \p{L} needs the third-party regex package
Other Flavours: Java, PHP, grep
Java: double escaping
Pattern p = Pattern.compile("\\d+\\.\\d+");The string literal "\\d" becomes the regex \dJava: find vs matches
Matcher m = p.matcher(s);
m.find(); // anywhere
m.matches(); // whole stringString.matches(regex) also requires a full matchJava: flags & groups
Pattern.compile("(?<year>\\d{4})", Pattern.CASE_INSENSITIVE);
m.group("year");Java: replace
s.replaceAll("(\\w+)@(\\w+)", "$2 at $1");Use Matcher.quoteReplacement for literal $ in replacementsPHP: delimiters
preg_match('/^\d{3}$/', $s);
preg_match('#^/api/v\d+/#', $path);PCRE patterns need delimiters; pick # or ~ when the pattern contains /PHP: modifiers
preg_match('/hello/iu', $s, $m);Modifiers go after the closing delimiter; u treats subject and pattern as UTF-8PHP: replace & escape
preg_replace('/\s+/', ' ', $s);
preg_quote($input, '/');Pass the delimiter to preg_quote so it is escaped toogrep basic vs extended
grep 'ab\+c' file # BRE (GNU)
grep -E 'ab+c|xyz' file # EREIn BRE, + ? | ( ) need backslashesgrep PCRE
grep -P '\d+(?=px)' style.cssLookarounds and \d; GNU grep only, not BSD/macOS grepUseful grep flags
grep -rnoiw -E 'todo|fixme' src/-r recursive, -n line numbers, -o only match, -i ignore case, -w whole word, -v invertsed / ripgrep
sed -E 's/([0-9]+)px/\1rem/g' file
rg '\bTODO\b' src/ripgrep uses Rust regex (no lookaround unless --pcre2)More Common Patterns
Email (pragmatic)
^[^\s@]+@[^\s@]+\.[^\s@]+$Sanity check only; confirm real addresses by sending an emailISO date (YYYY-MM-DD)
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$Does not reject Feb 30; validate with a date libraryIPv4 (0-255 strict)
^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$URL slug
^[a-z0-9]+(?:-[a-z0-9]+)*$Lowercase words separated by single hyphensUUID
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$Time 24h (HH:MM)
^([01]\d|2[0-3]):[0-5]\d$Semantic version
^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$Simplified; the official semver.org regex is stricterTrim whitespace
^\s+|\s+$Replace with an empty string (global)Free tools for this
Keep the references coming
One email a week: new and trending developer tools, fresh comparisons, and what shipped. Unsubscribe in one click.