On this page

Regex Cheat Sheet

Complete reference for regular expressions. Covers syntax, character classes, quantifiers, anchors, groups, lookaround, common patterns, and language-specific differences.


Character Classes

PatternMatchesExample
.Any character except newline (JS also excludes \r, U+2028, U+2029)a.c matches abc, a1c
\dDigit [0-9] (Unicode digits in Python 3 str and .NET)\d{3} matches 123
\DNon-digit [^0-9]\D+ matches abc
\wWord character [a-zA-Z0-9_] (Unicode letters in Python 3, .NET, Java with UNICODE_CHARACTER_CLASS)\w+ matches hello_123
\WNon-word character\W matches @, !
\sWhitespace [ \t\n\r\f\v] (plus Unicode spaces in JS, Python 3, .NET)\s+ matches spaces/tabs
\SNon-whitespace\S+ matches hello
[abc]Any of a, b, or c[aeiou] matches vowels
[^abc]Not a, b, or c[^0-9] matches non-digits
[a-z]Range: a through z[a-zA-Z] matches letters
[a-zA-Z0-9]AlphanumericSame as \w minus _ (ASCII mode)
[.], \.Literal dotInside [], most metacharacters are literal; escape only ], \, ^ (first), - (middle)
\p{L}, \p{Lu}Unicode letter / uppercase letterJS needs the u or v flag; not in Python re (use the regex package)
[[:alpha:]], [[:digit:]], [[:space:]]POSIX classesgrep, sed, awk, PCRE, Go, Rust; not JS, Python, Java (Java: \p{Alpha})

Quantifiers

PatternMeaningExample
*0 or more (greedy)ab*c matches ac, abc, abbc
+1 or more (greedy)ab+c matches abc, abbc (not ac)
?0 or 1 (optional)colou?r matches color, colour
{n}Exactly n\d{4} matches 2024
{n,}n or more\d{2,} matches 12, 123, 1234
{n,m}Between n and m\d{2,4} matches 12, 123, 1234
*?0 or more (lazy)".*?" matches shortest quoted string
+?1 or more (lazy)<.+?> matches single HTML tag
??0 or 1 (lazy)Prefer 0
*+0 or more (possessive)No backtracking (PCRE, Java, Ruby, Python 3.11+; not JS, .NET, Go, Rust)
{,n}0 to nPython, PCRE2 10.43+, Ruby; elsewhere it may be a literal, so write {0,n}

TIP

Greedy quantifiers match as much as possible, then backtrack. Lazy quantifiers match as little as possible. Use lazy when you need the shortest match, e.g. ".*?" to match individual quoted strings rather than everything between the first and last quote.


Anchors

PatternMatches
^Start of string (or line with m flag)
$End of string (or line with m flag)
\bWord boundary
\BNon-word boundary
\AStart of string (ignores multiline flag; not in JS)
\ZPython: very end of string. PCRE, Java, .NET, Ruby: end of string or before a final newline (not in JS)
\zVery end of string (PCRE, Java, .NET, Ruby, Go, Rust; Python 3.14+; not JS)

`$` and trailing newlines

In Python, PCRE, Java, .NET and Ruby, $ (without the multiline flag) also matches before a final \n, so ^\d+$ accepts "123\n". For strict validation use \A...\z (Python before 3.14: \A...\Z or re.fullmatch). In JavaScript and Go, $ without m means the very end.

\bword\b    → matches "word" but not "sword" or "wordy"
^Start      → matches "Start" only at beginning of string
end$        → matches "end" only at end of string

Groups & Capturing

PatternDescription
(abc)Capturing group
(?:abc)Non-capturing group
(?<name>abc)Named capturing group
\1Backreference to group 1
\k<name>Backreference to named group
(a|b)Alternation (a or b)
(?P<name>abc)Named group, Python syntax (also accepted by PCRE, Go, Rust; Python re does not accept (?<name>...))
(?P=name)Named backreference, Python syntax
(?>abc)Atomic group: no backtracking into it (PCRE, Java, .NET, Ruby, Python 3.11+)

Examples

# Capture date components
(\d{4})-(\d{2})-(\d{2})
# \1 = year, \2 = month, \3 = day

# Named groups
(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})

# Backreference: match repeated words
\b(\w+)\s+\1\b
# Matches "the the", "is is"

# Non-capturing group for alternation
(?:https?|ftp)://
# Groups without capturing

Lookahead & Lookbehind

Zero-width assertions that check for patterns without consuming characters.

PatternNameDescription
(?=abc)Positive lookaheadFollowed by abc
(?!abc)Negative lookaheadNOT followed by abc
(?<=abc)Positive lookbehindPreceded by abc
(?<!abc)Negative lookbehindNOT preceded by abc

Examples

# Password: at least one uppercase, one lowercase, one digit
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$

# Match "foo" only if NOT followed by "bar"
foo(?!bar)
# Matches "fooX", "foo ", but not "foobar"

# Match numbers NOT preceded by $
(?<!\$)\d+
# Matches "42" in "count: 42" but not in "$42"

# Extract value after "price: "
(?<=price:\s)\d+\.?\d*
# From "price: 19.99" matches "19.99" (the lookbehind text is not part of the match)

# Match word followed by comma
\w+(?=,)
# From "a, b, c" matches "a", "b"

WARNING

Lookbehind support differs by engine:

EngineLookbehind
JavaScript (ES2018+)Any pattern, including unbounded (?<=a+)
.NETAny pattern
JavaBounded variable length ((?<=a{1,5}) ok; */+ not reliably supported)
PCRE2 10.43+ (PHP 8.4, grep -P on new distros)Bounded variable length (max 255 chars by default); older PCRE: each alternative fixed length
Python reFixed width only: (?<=ab|cd) ok, (?<=a|bc) is an error. The regex package allows variable length
Ruby (Onigmo)Fixed length per alternative
Go, Rust regexNone (no lookaround at all)

Flags / Modifiers

FlagNameDescription
iCase-insensitivea matches A
gGlobalFind all matches, not just first (JS only; other languages use findall/FindAll/replace_all instead)
mMultiline^/$ match line start/end
sDotall / Single-line. matches newline too (Ruby calls this m)
uUnicodeEnable Unicode matching (JS: code points, \p{...})
xExtended / VerboseIgnore whitespace, allow comments (not in JS)
vUnicode sets (JS, ES2024)u plus class set operations: [\p{L}--[a-z]], [\p{L}&&\p{ASCII}]
ySticky (JS)Match only at lastIndex
dIndices (JS, ES2022)match.indices gives start/end of each group

Inline flags (?i), (?m), (?s), (?x) work in PCRE, Python, Java, .NET, Go and Rust. Scoped form (?i:abc) too. JavaScript supports only the scoped modifiers form (?i:abc) (ES2025), not a leading (?i).

Verbose Mode Example

# Python or PCRE with x flag
(?x)
^                   # Start of string
(?P<protocol>       # Protocol group
  https?|ftp        # http, https, or ftp
)
://                 # Separator
(?P<domain>         # Domain group
  [a-zA-Z0-9.-]+   # Domain characters
)
(?::(?P<port>\d+))? # Optional port
(?P<path>/\S*)?     # Optional path
$                   # End of string

Common Patterns

Email (Simplified)

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

URL

https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:/[^\s]*)?

IPv4 Address

\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b

IPv6 Address (Simplified)

(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}

Phone Number (US)

(?:\+1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}

Date (YYYY-MM-DD)

\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])

Time (HH:MM:SS, 24h)

(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?

Hex Color

#(?:[0-9a-fA-F]{3}){1,2}\b

# Also allow #RGBA and #RRGGBBAA
#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b

Trim / Collapse Whitespace

^\s+|\s+$          # leading/trailing whitespace (replace with "")
\s{2,}             # runs of whitespace (replace with " ")

Log Line (key=value pairs)

(\w+)=("[^"]*"|\S+)

Semantic Version

^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$

UUID

[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
# Lowercase only: add the i flag (or use [0-9a-fA-F]) for uppercase UUIDs

Slug (URL-friendly)

^[a-z0-9]+(?:-[a-z0-9]+)*$

HTML Tag

<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)</\1>

DANGER

Do not parse HTML with regex in production. Use a proper HTML parser. Regex is fine for quick extraction from well-known formats, but it cannot handle nested tags, attributes with >, or self-closing tags correctly.


Language-Specific Differences

JavaScript

// Literal syntax
const re = /pattern/flags;

// Constructor (dynamic patterns; double the backslashes in the string)
const re2 = new RegExp('\\d+', 'g');

// Escape user input before building a pattern (ES2025 RegExp.escape; older: escape by hand)
const safe = new RegExp(RegExp.escape(userInput));

// Methods
'hello'.match(/l+/g);           // ['ll']
'hello'.replace(/l/g, 'r');     // 'herro'
'hello'.search(/ll/);           // 2
/ll/.test('hello');              // true
'a,b,,c'.split(/,+/);           // ['a', 'b', 'c']

// Named groups (ES2018+)
const m = '2024-03-20'.match(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/);
m.groups.y; // '2024'

// matchAll (ES2020+)
const matches = [...'a1 b2 c3'.matchAll(/([a-z])(\d)/g)];

// Replace with group references or a function
'2024-03-20'.replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1');          // '20/03/2024'
'2024-03-20'.replace(/(?<y>\d+)-(?<m>\d+)/, '$<m>.$<y>');        // '03.2024-20'
'a1 b2'.replaceAll(/\d/g, d => d * 2);                           // 'a2 b4'

JS `g` and `lastIndex`

A regex with g or y keeps state in lastIndex. Reusing it with .test() alternates true/false on the same input. Don't share global regexes across calls, or reset re.lastIndex = 0.

Python

import re

# Match (beginning of string only)
re.match(r'\d+', '123abc')

# Search (anywhere in string)
re.search(r'\d+', 'abc123')

# Find all
re.findall(r'\d+', 'a1 b2 c3')        # ['1', '2', '3']

# Substitution
re.sub(r'\d+', 'X', 'a1 b2')           # 'aX bX'

# Compiled pattern (better for reuse)
pattern = re.compile(r'\d+')
pattern.findall('a1 b2')

# Named groups
m = re.search(r'(?P<year>\d{4})', '2024')
m.group('year')                         # '2024'

# Whole-string match (no anchors needed, no trailing-newline surprise)
re.fullmatch(r'\d+', '123')

# Replacement with group references: \1 or \g<name>
re.sub(r'(?P<y>\d{4})-(?P<m>\d{2})', r'\g<m>/\g<y>', '2024-03')   # '03/2024'

# Escape user input
re.escape('a.b*c')                      # 'a\\.b\\*c'

# Verbose mode
pattern = re.compile(r"""
    ^(\d{4})    # year
    -(\d{2})    # month
    -(\d{2})    # day
    $
""", re.VERBOSE)

Go

import "regexp"

// Compile (returns error)
re, err := regexp.Compile(`\d+`)

// MustCompile (panics on error), for package-level patterns
var digits = regexp.MustCompile(`\d+`)

digits.MatchString("abc123")             // true
digits.FindString("abc 123 def")         // "123"
digits.FindAllString("a1 b2 c3", -1)    // ["1", "2", "3"]
digits.ReplaceAllString("a1 b2", "X")   // "aX bX"

// Named groups ((?<name>) also accepted since Go 1.22)
date := regexp.MustCompile(`(?P<year>\d{4})-(?P<month>\d{2})`)
match := date.FindStringSubmatch("2024-03")
year := match[date.SubexpIndex("year")]   // "2024"

// Replacement: use ${1}, because "$1x" means the group named "1x"
date.ReplaceAllString("2024-03", "${month}/${year}")   // "03/2024"

WARNING

Go's regexp uses RE2, which does NOT support lookahead, lookbehind, or backreferences. This is by design for guaranteed linear-time matching. If you need these features, use a PCRE library.

Rust

use regex::Regex;

let re = Regex::new(r"\d+").unwrap();
re.is_match("abc123");                    // true
re.find("abc 123").unwrap().as_str();     // "123"

// Replace (returns Cow<str>)
re.replace_all("a1 b2", "X"); // "aX bX"

// Captures ((?<name>) also accepted since regex 1.9)
let date = Regex::new(r"(?P<y>\d{4})-(?P<m>\d{2})").unwrap();
let caps = date.captures("2024-03").unwrap();
&caps["y"]; // "2024"

// Replacement with named groups: ${name}
date.replace_all("2024-03", "${m}/${y}"); // "03/2024"

TIP

Go's regexp and Rust's regex crate are both RE2-style: linear time, no backreferences, no lookaround. Rust has fancy-regex (backtracking, supports both) when you need them.


Flavour Differences at a Glance

FeaturePOSIX ERE (grep -E, sed -E, awk)PCRE2 (grep -P, PHP)JavaScriptPython reJava.NETGo / Rust
\d, \w, \sNo (use [[:digit:]]); GNU grep accepts \w, \sYesYesYes (Unicode)YesYes (Unicode)Yes
Lazy *?NoYesYesYesYesYesYes
Backreferences \1BRE only (grep, sed without -E; GNU also in ERE)YesYesYesYesYesNo
LookaheadNoYesYesYesYesYesNo
LookbehindNoBoundedAnyFixedBoundedAnyNo
Named groupNo(?<n>), (?P<n>)(?<n>)(?P<n>)(?<n>)(?<n>)(?P<n>), (?<n>)
Atomic / possessiveNoBothNoBoth (3.11+)BothAtomic onlyNo
Unicode \p{L}NoYesWith u/vNo (regex pkg)YesYesYes
Replacement group ref\1 (sed)$1 / \1$1, $<n>\1, \g<n>$1, ${n}$1, ${n}${1}, ${n}
Worst-case timeLinear (DFA in GNU)ExponentialExponentialExponentialExponentialExponential (timeouts available)Linear

In POSIX BRE (plain grep, sed), + ? | ( ) { } are literal; write \+ \? \| \( \) \{ \} (GNU extensions). Use grep -E / sed -E to avoid the backslashes.


Performance Tips

TipWhy
Anchor patterns with ^ and $^ stops the engine retrying at every position; $ alone does not
Avoid .* at the startForces engine to try every position
Use non-capturing groups (?:...)Avoids unnecessary memory allocation
Use possessive quantifiers *+ when safePrevents catastrophic backtracking
Use atomic groups (?>...) when safeSame as possessive, supported by more engines (incl. .NET)
Prefer character classes over alternation[aeiou] is faster than (a|e|i|o|u)
Use a linear-time engine for untrusted inputRE2/Go/Rust, .NET RegexOptions.NonBacktracking, V8's --enable-experimental-regexp-engine
Set a timeout where supported.NET matchTimeout, Java: interrupt-aware CharSequence, Python regex package timeout=
Compile and reuse patternsAvoid recompiling in loops
Beware of catastrophic backtracking(a+)+ on "aaaaaaaaaaaaaaX" is O(2^n)

DANGER

Catastrophic backtracking is a real security vulnerability (ReDoS). Never use user-supplied patterns without timeout or input length limits.


Test Yourself
  1. What is the difference between * and + quantifiers? * matches 0 or more; + matches 1 or more.

  2. How do you make a quantifier lazy (match as little as possible)? Add ? after it: *?, +?, ??

  3. What does \b match? A word boundary (the position between a word character and a non-word character).

  4. How do you create a non-capturing group? (?:pattern) -- groups without saving the match.

  5. What is a positive lookahead and its syntax? (?=pattern) -- asserts that the position is followed by the pattern, without consuming characters.

  6. What regex flag makes . match newline characters? s (dotall / single-line mode).

  7. How do you match a literal dot in regex? Escape it: \.

  8. What backreference syntax matches a previously captured group? \1 for group 1, \k<name> for named groups.

  9. What Python function finds all matches in a string? re.findall(r'\d+', text)

  10. Why is (a+)+ dangerous on certain inputs? It causes catastrophic backtracking (exponential time) on inputs like "aaaaaX".

Common Gotchas

  • Catastrophic backtracking (ReDoS). Patterns like (a+)+, (a|aa)+, or (.*a){10} can take exponential time. Never use user-supplied patterns without timeouts.
  • Greedy .* matches too much. ".*" matches from the first quote to the LAST quote. Use ".*?" for the shortest match, or better "[^"]*", which cannot backtrack across quotes.
  • Go's regexp does not support lookahead/lookbehind. It uses RE2 for guaranteed linear-time matching. Use a PCRE library if you need these features.
  • Forgetting to anchor patterns. Without ^ and $, a pattern matches anywhere in the string. An email regex without anchors will "validate" xxinvalid@a.comxxx.
  • $ accepts a trailing newline in Python, PCRE, Java, .NET and Ruby. "admin\n" passes ^admin$. Use \z / re.fullmatch for validation.
  • Alternation binds loosest. ^cat|dog$ means (^cat)|(dog$). Write ^(?:cat|dog)$.
  • Unescaped user input in a pattern. . and * in a search box become metacharacters (and a ReDoS vector). Escape with re.escape, RegExp.escape, regexp.QuoteMeta, Pattern.quote.
  • Same pattern, different flavour. \d matches Arabic-Indic digits in Python 3 and .NET; \w is ASCII-only in JavaScript even with u; grep without -E treats + as a literal. Test in the engine you deploy.

One-Liner Summary

Regular expressions are a pattern-matching language for text -- master character classes, quantifiers, groups, and lookaround to search, validate, and transform strings in any language.

Last updated: 2026-11-09