Skip to main content
CalcHive
Developer GuidesMar 15, 20266 min read

Regex Cheat Sheet: Common Patterns Every Developer Needs

A practical reference of regex patterns for email validation, password strength, phone numbers, dates, and more. Copy-paste examples included.

Regular expressions are one of those tools that every developer needs but few have fully memorized. Whether you're validating user input, parsing log files, or doing search-and-replace across a codebase, the right regex pattern saves hours of manual work. This cheat sheet covers the patterns you'll actually use day to day, with copy-paste examples you can drop straight into your code.

Regex Basics: The Building Blocks

Before diving into specific patterns, here's a quick refresher on the fundamental metacharacters that make regex work.

SymbolMeaningExample
.Any character except newlinea.c matches "abc", "a1c"
^Start of string^Hello matches "Hello world"
$End of stringworld$ matches "Hello world"
*Zero or more of the previousab*c matches "ac", "abc", "abbc"
+One or more of the previousab+c matches "abc", "abbc" (not "ac")
?Zero or one of the previouscolou?r matches "color" and "colour"
\dAny digit (0-9)\d3 matches "123"
\wWord character (a-z, A-Z, 0-9, _)\w+ matches "hello_world"
\sWhitespace (space, tab, newline)\s+ matches any whitespace run

Email and URL Validation Patterns

Email validation with regex is a surprisingly deep topic. The RFC-compliant pattern is absurdly long. In practice, this simplified version catches the vast majority of valid email addresses while rejecting obvious garbage.

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

// Breakdown:
// ^[a-zA-Z0-9._%+-]+   - Local part: letters, digits, dots, underscores, etc.
// @                      - The @ symbol
// [a-zA-Z0-9.-]+        - Domain name: letters, digits, dots, hyphens
// \.[a-zA-Z]{2,}$      - TLD: dot followed by 2+ letters

For URL matching, this pattern handles most common cases including optional protocol, subdomains, and paths:

// URL validation
^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$

// Matches:
// https://example.com
// http://sub.example.com/path?q=1
// example.com/page

Test these patterns instantly with the Regex Tester or validate email addresses using the Email Validator.

Number and Date Patterns

Matching numbers sounds simple until you need to handle decimals, negatives, thousands separators, or specific ranges. Here are the patterns that cover real-world scenarios.

// Integer (positive or negative)
^-?\d+$

// Decimal number (optional decimal part)
^-?\d+(\.\d+)?$

// Number with commas (e.g., 1,234,567.89)
^-?\d{1,3}(,\d{3})*(\.\d+)?$

// Date: YYYY-MM-DD
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

// Date: MM/DD/YYYY
^(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/\d{4}$

// Time: HH:MM (24-hour)
^([01]\d|2[0-3]):[0-5]\d$

// Time: HH:MM:SS with optional AM/PM
^(0?[1-9]|1[0-2]):[0-5]\d(:[0-5]\d)?\s?(AM|PM|am|pm)?$

Note that regex date validation only checks the format, not whether the date is actually valid. February 30th would pass the format check. For real date validation, parse the string with your language's date library after the regex confirms the format.

Password Strength and Input Validation

Password requirements are a common use case for regex. Here are patterns for various strength levels, from basic to strict.

// Minimum 8 characters
^.{8,}$

// At least one uppercase, one lowercase, one digit, min 8 chars
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$

// Strong: uppercase, lowercase, digit, special char, min 12 chars
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{12,}$

// Username: alphanumeric + underscore, 3-20 chars
^[a-zA-Z0-9_]{3,20}$

// Slug (URL-friendly string)
^[a-z0-9]+(-[a-z0-9]+)*$

// Hex color code
^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$

The (?=...) syntax is a lookahead assertion. It checks whether a condition is true at a given position without consuming characters. Stacking multiple lookaheads lets you enforce several requirements at once, regardless of the order characters appear in the string.

Need to generate secure passwords to test against? Try the Slugify tool to create URL-friendly strings from any text.

Search and Replace Patterns

Regex really shines when you need to transform text, not just match it. Capture groups let you reference matched parts in the replacement string.

// Swap first and last name
// Input:  "Smith, John"
// Pattern: ^(\w+),\s*(\w+)$
// Replace: $2 $1
// Output: "John Smith"

// Convert dates from MM/DD/YYYY to YYYY-MM-DD
// Pattern: (\d{2})\/(\d{2})\/(\d{4})
// Replace: $3-$1-$2

// Remove duplicate whitespace
// Pattern: \s+
// Replace: (single space)

// Wrap words in HTML tags
// Pattern: \b(\w+)\b
// Replace: <span>$1</span>

// Extract domain from email
// Pattern: @([\w.-]+)
// Group 1 captures the domain

// Remove HTML tags
<[^>]*>

Capture groups are numbered starting at 1, based on the order of their opening parentheses. Named groups like (?<name>...) make complex patterns more readable, especially when you have more than three or four groups.

Phone Numbers, IPs, and Other Formats

These patterns handle common data formats you'll encounter in web applications and data processing.

// US phone number (flexible format)
^\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
// Matches: (555) 123-4567, 555-123-4567, +1 555 123 4567

// IPv4 address
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$

// IPv4 with CIDR notation
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)\/(3[0-2]|[12]?\d)$

// MAC address
^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$

// Credit card number (basic, spaces or dashes allowed)
^\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}$

// SSN format (US)
^\d{3}-\d{2}-\d{4}$

// ZIP code (US, with optional +4)
^\d{5}(-\d{4})?$

Common Pitfalls and Tips

After years of debugging regex issues, these are the mistakes that come up most often.

  • Forgetting to escape special characters: Dots, parentheses, brackets, and backslashes all have special meaning. Use \. to match a literal dot.
  • Greedy vs. lazy matching: By default, .* is greedy and matches as much as possible. Add ? to make it lazy: .*? matches as little as possible. This matters when parsing HTML or extracting quoted strings.
  • Not anchoring your patterns: Without ^ and $, your pattern can match a substring instead of the whole string. /\d+/ matches the "123" inside "abc123def".
  • Catastrophic backtracking: Nested quantifiers like (a+)+$ can cause exponential matching time on certain inputs. Avoid nesting* and + inside groups that also repeat.
  • Testing only the happy path: Always test your regex against edge cases, empty strings, and intentionally malformed input.

The best way to build and debug regex is interactively. Paste your pattern and test strings into the Regex Tester to see matches highlighted in real time, with capture group breakdowns and detailed explanations of what each part of your pattern does.

More Articles

UK Take-Home Pay 2025/26: What Changed and What It Means for You

A breakdown of the 2025/26 tax year changes, frozen thresholds, fiscal drag, and worked examples showing your actual take-home pay at every salary level.

Base64, URL Encoding, and JWT: A Developer's Quick Reference

When to use Base64 vs URL encoding, how JWTs actually work, and the encoding mistakes that break production APIs.

MD5, SHA-256, bcrypt: Which Hash Do You Actually Need?

A no-nonsense breakdown of hash functions. What each one does, when to use it, and the one you should never use for passwords.

JSON vs YAML vs CSV vs XML: Pick the Right Format

Each data format exists for a reason. Here's when to reach for each one, how to convert between them, and the gotchas that trip people up.

Understanding Cron Expressions: A Practical Guide

Learn cron syntax from the ground up. Covers the five-field format, common schedules, platform differences, and the mistakes that trip people up.

BMI Chart: What Your Number Actually Means

A clear explanation of BMI categories, the formula behind the number, the limitations of BMI, and when other health metrics are more useful.

Compound Interest Explained: How Your Money Grows Over Time

The compound interest formula broken down with real examples, the Rule of 72, and practical strategies for making compounding work in your favor.

UUID vs Nano ID vs CUID: Choosing the Right ID Format

Compare UUID v4, UUID v7, Nano ID, and CUID2. Learn the tradeoffs around length, sortability, collision resistance, and database performance.

Will You Ever Repay Your Student Loan? Here's How to Find Out

Most Plan 2 borrowers will never repay in full. Learn how UK student loan repayment works, see worked examples at different salaries, and find out whether overpaying makes sense.

Complete Guide to Metric and Imperial Conversions

Reference tables and mental math tricks for converting between metric and imperial units. Covers length, weight, temperature, volume, and area.