The Practical Regex Cheat Sheet
8 min read

The Practical Regex Cheat Sheet

A no-nonsense reference for regular expressions you'll actually use.

regexprogrammingreferencetutorial
Share:

The Practical Regex Cheat Sheet

A no-nonsense reference for regular expressions you'll actually use.


Quick Reference Table

PatternMatchesExample
.Any character except newlinea.c → "abc", "a1c"
\dDigit (0-9)\d{3} → "123"
\DNon-digit\D+ → "abc"
\wWord character (a-z, A-Z, 0-9, _)\w+ → "hello_123"
\WNon-word character\W → "@", " "
\sWhitespace (space, tab, newline)\s+ → " "
\SNon-whitespace\S+ → "hello"
^Start of string/line^Hello → "Hello world"
$End of string/lineworld$ → "Hello world"
\bWord boundary\bcat\b → "cat" not "catalog"
*0 or moreab*c → "ac", "abc", "abbc"
+1 or moreab+c → "abc", "abbc"
?0 or 1 (optional)colou?r → "color", "colour"
{n}Exactly n times\d{4} → "2024"
{n,m}Between n and m times\d{2,4} → "12", "123", "1234"
[abc]Any of a, b, or c[aeiou] → vowels
[^abc]Not a, b, or c[^0-9] → non-digits
[a-z]Range a to z[A-Za-z] → letters
(abc)Capture group(\d+)-(\d+) → captures both
(?:abc)Non-capturing group(?:Mr|Ms)\. → no capture
a|ba or bcat|dog → "cat" or "dog"
\Escape special character\. → literal "."

Patterns You'll Use Daily

Email Address

[\w.-]+@[\w.-]+\.\w{2,}

Matches: user@example.com, first.last@sub.domain.co.uk

Note: Full email validation is complex. For real validation, use your language's email library.

URL

https?:\/\/[\w.-]+(?:\/[\w./-]*)?(?:\?[\w=&-]*)?

Matches: https://example.com, http://sub.domain.com/path?query=value

Phone Number (US)

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

Matches: (555) 123-4567, 555.123.4567, 5551234567

Date (Various Formats)

# YYYY-MM-DD (ISO)
\d{4}-\d{2}-\d{2}

# MM/DD/YYYY or DD/MM/YYYY
\d{1,2}\/\d{1,2}\/\d{4}

# Month DD, YYYY
(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},?\s+\d{4}

Time

# 24-hour (HH:MM or HH:MM:SS)
\d{2}:\d{2}(?::\d{2})?

# 12-hour with AM/PM
\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM|am|pm)

IP Address (IPv4)

\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b

Matches: 192.168.1.1, 10.0.0.255

Note: This matches syntactically valid IPs. Values like 999.999.999.999 would match. For strict validation, check each octet is 0-255.

Hex Color

#[0-9A-Fa-f]{3,8}\b

Matches: #FFF, #ffffff, #FF5733, #FF573399

UUID/GUID

[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}

Matches: 550e8400-e29b-41d4-a716-446655440000

Credit Card (Basic)

\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}

Matches: 4111111111111111, 4111-1111-1111-1111, 4111 1111 1111 1111

ZIP Code (US)

\b\d{5}(?:-\d{4})?\b

Matches: 12345, 12345-6789

Username

^[a-zA-Z][a-zA-Z0-9_-]{2,19}$

Rules: Starts with letter, 3-20 characters, allows letters, numbers, underscore, hyphen.

Password Strength

# At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

Uses lookaheads to check multiple conditions.

HTML Tag

<[^>]+>

Matches: <div>, <img src="x">, </span>

Warning: Don't parse HTML with regex for complex tasks. Use a proper HTML parser.

Extract Content from Tags

<(\w+)[^>]*>(.*?)<\/\1>

Captures: Tag name in group 1, content in group 2.

Numbers

# Integers (positive and negative)
-?\d+

# Decimals
-?\d+\.?\d*

# Scientific notation
-?\d+\.?\d*[eE][+-]?\d+

# With thousand separators
\d{1,3}(?:,\d{3})*(?:\.\d+)?

File Path

# Unix path
(?:\/[\w.-]+)+

# Windows path
[A-Z]:\\(?:[\w.-]+\\)*[\w.-]+

# Filename with extension
[\w.-]+\.\w{1,10}

Common Operations

Extract All Matches

const text = "Contact: john@email.com or jane@email.com";
const emails = text.match(/[\w.-]+@[\w.-]+\.\w+/g);
// ["john@email.com", "jane@email.com"]

Replace with Captured Groups

// Reformat date from MM/DD/YYYY to YYYY-MM-DD
const text = "Date: 01/15/2024";
const result = text.replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$3-$1-$2');
// "Date: 2024-01-15"

Split by Pattern

const text = "apple,banana;cherry|date";
const fruits = text.split(/[,;|]/);
// ["apple", "banana", "cherry", "date"]

Validate (Full Match)

const emailPattern = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
const isValid = emailPattern.test("user@example.com"); // true
const isInvalid = emailPattern.test("not an email"); // false

Non-Greedy Matching

// Greedy (default) - matches as much as possible
"<div>first</div><div>second</div>".match(/<div>.*<\/div>/);
// ["<div>first</div><div>second</div>"]

// Non-greedy (add ?) - matches as little as possible
"<div>first</div><div>second</div>".match(/<div>.*?<\/div>/g);
// ["<div>first</div>", "<div>second</div>"]

Lookahead and Lookbehind

Advanced patterns that check context without including it in the match.

Positive Lookahead (?=...)

Match only if followed by pattern:

\d+(?=\s*USD)

In "100 USD, 200 EUR, 300 USD" → matches "100", "300" (not "200")

Negative Lookahead (?!...)

Match only if NOT followed by pattern:

\d+(?!\s*USD)

In "100 USD, 200 EUR, 300 USD" → matches "200"

Positive Lookbehind (?<=...)

Match only if preceded by pattern:

(?<=\$)\d+

In "$100, €200, $300" → matches "100", "300"

Negative Lookbehind (?<!...)

Match only if NOT preceded by pattern:

(?<!\$)\d+

In "$100, €200, $300" → matches "200"

Practical Example: Password Rules

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$

Translation:

  • (?=.*[a-z]) - must contain lowercase
  • (?=.*[A-Z]) - must contain uppercase
  • (?=.*\d) - must contain digit
  • .{8,} - at least 8 characters

Flags/Modifiers

FlagMeaningExample
gGlobal - find all matches/cat/g
iCase-insensitive/cat/i matches "Cat"
mMultiline - ^ and $ match line boundaries/^start/m
sDotall - . matches newlines/a.b/s matches "a\nb"
uUnicode - proper Unicode handling/\p{L}/u
// Combining flags
const pattern = /hello/gi; // global + case-insensitive

// With RegExp constructor
const pattern = new RegExp('hello', 'gi');

Named Capture Groups

Give captures meaningful names instead of numbers:

const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = "2024-01-15".match(pattern);

console.log(match.groups.year);  // "2024"
console.log(match.groups.month); // "01"
console.log(match.groups.day);   // "15"

// In replacements
"2024-01-15".replace(pattern, '$<day>/$<month>/$<year>');
// "15/01/2024"

Escaping Special Characters

These characters have special meaning and need escaping with \:

. * + ? ^ $ { } [ ] \ | ( )
// To match literal "1+1=2"
const pattern = /1\+1=2/;

// To match "(example)"
const pattern = /\(example\)/;

// To match "price: $100"
const pattern = /price: \$\d+/;

Programmatically escape a string:

function escapeRegex(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

const userInput = "What? (yes!)";
const pattern = new RegExp(escapeRegex(userInput));

Performance Tips

  1. Be specific - /\d{4}-\d{2}-\d{2}/ is faster than /.*\d.*-.*\d.*/

  2. Avoid catastrophic backtracking:

    # Bad - exponential backtracking
    (a+)+b
    
    # Good - no nested quantifiers on same character
    a+b
    
  3. Use non-capturing groups when you don't need the capture:

    # Faster (no capture overhead)
    (?:https?|ftp)://
    
    # Slower (creates capture)
    (https?|ftp)://
    
  4. Anchor when possible:

    # Faster - starts from beginning
    ^https://
    
    # Slower - checks every position
    https://
    
  5. Compile once, use many:

    // Bad - recompiles every iteration
    for (const item of items) {
      if (/pattern/.test(item)) { ... }
    }
    
    // Good - compile once
    const pattern = /pattern/;
    for (const item of items) {
      if (pattern.test(item)) { ... }
    }
    

Language-Specific Notes

JavaScript

// Literal syntax
const pattern = /abc/gi;

// Constructor (for dynamic patterns)
const pattern = new RegExp('abc', 'gi');

// Methods
pattern.test(string);     // Returns boolean
string.match(pattern);    // Returns matches array
string.replace(pattern, replacement);
string.split(pattern);

Python

import re

# Compile for reuse
pattern = re.compile(r'\d+')

# Methods
re.search(pattern, string)   # First match
re.match(pattern, string)    # Match at start only
re.findall(pattern, string)  # All matches as list
re.sub(pattern, repl, string) # Replace

Java

import java.util.regex.*;

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("abc123");

boolean found = matcher.find();
String match = matcher.group();

Go

import "regexp"

pattern := regexp.MustCompile(`\d+`)

// Methods
pattern.MatchString(str)      // bool
pattern.FindString(str)       // first match
pattern.FindAllString(str, -1) // all matches
pattern.ReplaceAllString(str, repl)

Testing Your Regex

Always test with:

  • Positive cases - inputs that should match
  • Negative cases - inputs that should NOT match
  • Edge cases - empty strings, very long strings, special characters
  • Real-world data - actual examples from your use case

Use our Regex Tester to interactively build and test patterns with instant feedback and match highlighting. Features include:

  • Live matching as you type
  • Capture group visualization
  • Match highlighting
  • Common pattern library
  • Export to multiple languages

Also check out our Regex Cheatsheet Tool for a quick reference while you work.


Quick Debugging Checklist

When your regex doesn't work:

  1. Escaping - Did you escape special characters?
  2. Flags - Do you need g, i, m?
  3. Anchors - Should it match the whole string (^...$)?
  4. Greedy vs non-greedy - Add ? after quantifiers for minimal matching
  5. Character classes - Is \d what you meant, or do you need [0-9] with specific ranges?

Last updated: January 2025

Related Tools

Related Articles