🧠 AI Computer Institute
Content is AI-generated for educational purposes. Verify critical information independently. A bharath.ai initiative.

Regular Expressions Cheat Sheet

programmingGrades 9-127 sections

Basic Syntax

# Literal characters
/abc/           # Matches "abc" exactly

# Special characters (escape with backslash)
/./ (dot)       # Matches any character except newline
/./            # Matches literal dot
/*/            # Matches literal asterisk
/\n/           # Matches newline
/	/            # Matches tab
/$/            # Literal $ (end anchor)
/^/            # Literal ^ (start anchor)

# Anchors
/^start/        # Start of string
/end$/          # End of string
/^alone$/       # Entire string is "alone"

# Word boundary
/hello/     # "hello" as whole word
/word/        # Word starting with "word"
/word/        # Word ending with "word"

Character Classes

# Predefined classes
/d/            # Digit [0-9]
/D/            # Non-digit [^0-9]
/w/            # Word char [a-zA-Z0-9_]
/W/            # Non-word char
/s/            # Whitespace (space, tab, newline)
/S/            # Non-whitespace

# Custom classes (inside [])
/[abc]/         # a OR b OR c
/[a-z]/         # Lowercase letters
/[A-Z]/         # Uppercase letters
/[0-9]/         # Digits (same as d)
/[a-zA-Z]/      # Letters
/[a-zA-Z0-9]/   # Alphanumeric
/[^abc]/        # NOT a, b, or c (negation)
/[a-z^]/        # Letters OR literal ^ (inside [])

# Ranges
/[0-5]/         # 0 through 5
/[a-m]/         # a through m
/[A-D]/         # A through D

# Common combinations
/[a-zA-Z0-9_-]/  # Typical username chars
/[^s]/           # Non-whitespace

Quantifiers

# Zero or one
/colou?r/       # Matches "color" or "colour"
/a?b/           # b or ab

# Zero or more
/a*/            # "", "a", "aa", "aaa", ...
/go*/           # "g", "go", "goo", "gooo", ...

# One or more
/a+/            # "a", "aa", "aaa", ... (but not "")
/go+/           # "go", "goo", "gooo", ...

# Exact count
/a{3}/          # Exactly "aaa"
/a{2,4}/        # "aa", "aaa", or "aaaa"
/a{2,}/         # At least 2: "aa", "aaa", ...

# Greedy vs Non-greedy
/<.+>/          # Greedy: matches longest
/<.+?>/         # Non-greedy: matches shortest
/<.*?>/         # Match between < and > (shortest)

# Examples
/[0-9]{3}-[0-9]{2}-[0-9]{4}/  # SSN: 123-45-6789
/d{5}(-d{4})?/               # Zip code: 12345 or 12345-6789

Groups & Alternation

# Groups (parentheses)
/(abc)+/        # "abc", "abcabc", "abcabcabc", ...
/(cat|dog)/     # "cat" or "dog"
/(https?://)/  # "http://" or "https://"

# Capturing groups
/(d{3})-(d{4})/  # (123)-(4567) - groups captured
// Usage in replace:
"123-4567".replace(/(d{3})-(d{4})/, "$2-$1")  // "4567-123"

# Non-capturing groups
/(?:abc)+/      # Group but don't capture (more efficient)

# Alternation (pipe |)
/cat|dog|bird/  # One of these
/(cat|dog) food/  # "cat food" or "dog food"
/on|off/        # "on" or "off"

# Lookahead
/d+(?=px)/     # Digits followed by "px" (doesn't include px)
/foo(?!bar)/    # "foo" NOT followed by "bar"

# Lookbehind
/(?<=€)d+/     # Digits preceded by €
/(?

Common Patterns

# Email (simple)
/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}/

# URL
/https?://[^s]+/

# Phone (US)
/(d{3})[-.]?(d{3})[-.]?(d{4})/
// Matches: 123-456-7890, 123.456.7890, (123)456-7890

# Date (YYYY-MM-DD)
/d{4}-d{2}-d{2}/

# Time (HH:MM:SS)
/([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/

# IPv4 Address
/(d{1,3}.){3}d{1,3}/

# Hex color
/#[0-9a-fA-F]{6}/

# HTML/XML tag
/<[^>]+>/

# Username (alphanumeric + underscore, 3-16 chars)
/^[a-zA-Z0-9_]{3,16}$/

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

# Whitespace
/s+/           # One or more whitespace

# Line endings
/
|
|
/    # CRLF, CR, or LF

JavaScript Regex Methods

// Create regex
const re = /pattern/flags;
const re = new RegExp("pattern", "flags");

// Flags
i   // Case-insensitive
g   // Global (find all)
m   // Multiline
s   // Dotall (. matches newline)
u   // Unicode
y   // Sticky

// Test (returns boolean)
/hello/.test("hello world");  // true

// Exec (returns match object)
const match = /(d+)/.exec("abc123def");
console.log(match[1]);  // "123"

// String methods
"hello".match(/l+/);          // ["ll"]
"hello world".match(/w+/g);  // ["hello", "world"]

"hello".search(/l+/);         // 2 (index)

"hello".replace(/l/, "L");    // "heLlo"
"hello".replace(/l/g, "L");   // "heLLo"
"hello".replaceAll("l", "L"); // "heLLo"

"a,b,c".split(/,/);           // ["a", "b", "c"]

// Advanced replacement
"123-456-7890".replace(/(d{3})-(d{3})-(d{4})/, "($1) $2-$3");
// "(123) 456-7890"

Debugging & Tips

// Test regex online: regex101.com, regexpal.com

// Escape special chars
function escapeRegex(str) {
    return str.replace(/[.*+?^$()|[\]]/g, (c) => '\\' + c);
}

// Common mistakes:
// ❌ /[a-z-]/      // Wrong: dash at end is literal
// ✓  /[a-z-]/    // Correct: escaped dash
// or /[a-z-]/     // Correct: dash at start/end is literal

// ❌ /./           // Matches any char except newline
// ✓  /[sS]/     // Matches ANY char including newline

// ❌ /^abc/        // In multiline, matches each line
// ✓  /Aabc/      // Always start of string

// Performance tips:
// - Use non-capturing groups when not needed: (?:...)
// - Avoid catastrophic backtracking: use atomic groups
// - Compile regex outside loops
// - Use specific patterns over general ones

// Example: compile outside loop
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
for (let email of emails) {
    if (emailRegex.test(email)) { ... }
}

More Cheat Sheets