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 newline
Digit\dDigit [0-9]
Non-digit\DNon-digit
Word\wWord char [a-zA-Z0-9_]
Non-word\WNon-word char
Space\sWhitespace
Non-space\SNon-whitespace
Set[abc]Any of a, b, or c
Negated set[^abc]Not a, b, or c
Range[a-z]Range a to z

Quantifiers

Star*0 or more
Plus+1 or more
Optional?0 or 1
Exact{n}Exactly n
Min{n,}n or more
Range{n,m}Between n and m
Lazy star*?0 or more (lazy)
Lazy plus+?1 or more (lazy)

Anchors & Boundaries

Start^Start of string
End$End of string
Boundary\bWord boundary
Non-boundary\BNon-word boundary

Groups & References

Group(abc)Capture group
Non-capture(?:abc)Non-capture group
Named(?<name>abc)Named group
Back-ref\1Back-reference
Ora|bAlternation (OR)

Lookaheads & Lookbehinds

Lookahead(?=abc)Positive lookahead
Neg lookahead(?!abc)Negative lookahead
Lookbehind(?<=abc)Positive lookbehind
Neg lookbehind(?<!abc)Negative lookbehind

Common Patterns

Email[\w.-]+@[\w.-]+\.\w+
URLhttps?://[\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, .NET
Global (JS)/\d+/gFind all matches with matchAll/replace; other languages use findall/replaceAll instead
Multiline/^\w+/m (?m)^ and $ match at every line start/end, not just the string
Dot matches newline/a.b/s (?s)Called DOTALL in Python and Java
Verbose / 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 operations
Sticky (JS)/foo/yMatch only at lastIndex

Python re Module

Raw stringsimport re pattern = r"\d+\.\d+"r"..." stops Python from interpreting backslashes before re sees them
search (anywhere)m = re.search(r"\d+", "order 42") m.group() # '42'Returns a Match or None
match (at start)re.match(r"\d+", "42 apples") # match re.match(r"\d+", "x42") # None
fullmatch (whole string)re.fullmatch(r"[a-z0-9-]+", slug)Best for validation; no need for ^...$
findallre.findall(r"\d+", "a1 b22 c333") # ['1', '22', '333']With groups it returns the groups (tuples if several)
finditerfor 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 functionre.sub(r"\d+", lambda m: str(int(m.group()) * 2), s)
splitre.split(r"[,;]\s*", "a, b;c") # ['a', 'b', 'c']
Named groupsm = 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 subre.sub(r"(?P<y>\d{4})-(?P<m>\d{2})", r"\g<m>/\g<y>", s)
Flagsre.search(r"^error", log, re.I | re.M)re.I ignorecase, re.M multiline, re.S dotall, re.X verbose
Compile & reuseDATE = re.compile(r"\d{4}-\d{2}-\d{2}") DATE.findall(text)
Escape user inputre.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 escapingPattern p = Pattern.compile("\\d+\\.\\d+");The string literal "\\d" becomes the regex \d
Java: find vs matchesMatcher m = p.matcher(s); m.find(); // anywhere m.matches(); // whole stringString.matches(regex) also requires a full match
Java: flags & groupsPattern.compile("(?<year>\\d{4})", Pattern.CASE_INSENSITIVE); m.group("year");
Java: replaces.replaceAll("(\\w+)@(\\w+)", "$2 at $1");Use Matcher.quoteReplacement for literal $ in replacements
PHP: delimiterspreg_match('/^\d{3}$/', $s); preg_match('#^/api/v\d+/#', $path);PCRE patterns need delimiters; pick # or ~ when the pattern contains /
PHP: modifierspreg_match('/hello/iu', $s, $m);Modifiers go after the closing delimiter; u treats subject and pattern as UTF-8
PHP: replace & escapepreg_replace('/\s+/', ' ', $s); preg_quote($input, '/');Pass the delimiter to preg_quote so it is escaped too
grep basic vs extendedgrep 'ab\+c' file # BRE (GNU) grep -E 'ab+c|xyz' file # EREIn BRE, + ? | ( ) need backslashes
grep PCREgrep -P '\d+(?=px)' style.cssLookarounds and \d; GNU grep only, not BSD/macOS grep
Useful grep flagsgrep -rnoiw -E 'todo|fixme' src/-r recursive, -n line numbers, -o only match, -i ignore case, -w whole word, -v invert
sed / ripgrepsed -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 email
ISO 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 library
IPv4 (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 hyphens
UUID^[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 stricter
Trim 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.