·11 min read·Regular Expressions

Regex Cheat Sheet: 20 Patterns Every Developer Needs

The 20 most useful regular expression patterns for email, URL, phone, date, IP address, password, and more. Copy-paste ready with explanations and live testing.

Try our free Regex Tester

Test any regex pattern with real-time highlighting and plain-English explanations.

Open Tool

Why Every Developer Needs Regex

Regular expressions (regex) are one of the most powerful and universally applicable tools in a developer's toolkit. Whether you're validating user input, parsing log files, extracting data from text, or performing complex search-and-replace operations, regex lets you describe text patterns in a concise, machine-readable format.

Every major programming language supports regex natively -- JavaScript, Python, Java, Go, PHP, Ruby, C#, and Rust all have built-in regex engines. Text editors like VS Code, Sublime Text, and Vim use regex for find-and-replace. Command-line tools like grep, sed, and awk are built entirely around regex patterns.

The challenge is that regex syntax is dense and easy to forget. This cheat sheet gives you the 20 most commonly needed patterns, organized by use case, so you can copy-paste them when you need them. You can test any of these patterns live using our Regex Tester -- it highlights matches in real time and explains what each part of the pattern does.

Regex Syntax Quick Reference

Before diving into specific patterns, here is a quick reference of the most common regex syntax elements:

SymbolMeaningExample
.Any character except newlinea.c matches "abc", "a1c"
^Start of string^Hello matches "Hello world"
$End of stringend$ matches "the end"
*0 or moreab*c matches "ac", "abc", "abbc"
+1 or moreab+c matches "abc", "abbc"
?0 or 1 (optional)colou?r matches "color", "colour"
{n,m}Between n and m timesa{2,4} matches "aa", "aaa", "aaaa"
[abc]Character class (any of a, b, c)[aeiou] matches any vowel
[^abc]Negated character class[^0-9] matches non-digits
\dDigit (0-9)\d+ matches "123"
\wWord character (a-z, A-Z, 0-9, _)\w+ matches "hello_42"
\sWhitespace (space, tab, newline)\s+ matches spaces
(a|b)Alternation (a or b)(cat|dog) matches "cat" or "dog"

Validation Patterns (Email, URL, Phone, IP)

These patterns are designed to validate common input formats. Test them live with our Regex Tester.

Pattern 1: Email Address

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

Matches: user@example.com, john.doe+work@company.co.uk

Covers the vast majority of real-world email addresses. Allows dots, hyphens, underscores, and plus signs in the local part. Requires at least a two-character TLD.

Pattern 2: URL (HTTP/HTTPS)

^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)$

Matches: https://example.com, http://www.site.co/path?q=1

Matches URLs starting with http:// or https://, with an optional www prefix, a domain, and an optional path with query parameters.

Pattern 3: US Phone Number

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

Matches: (555) 123-4567, +1-555-123-4567, 5551234567

Accepts US phone numbers in various formats -- with or without country code, parentheses, dashes, dots, or spaces as separators.

Pattern 4: IPv4 Address

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

Matches: 192.168.1.1, 10.0.0.255, 0.0.0.0

Validates each octet is between 0 and 255. Rejects values like 999.999.999.999 or 256.1.1.1.

Pattern 5: Strong Password

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

Matches: MyP@ss1word, Str0ng!Pass

Requires at least 8 characters, one uppercase letter, one lowercase letter, one digit, and one special character. Uses lookaheads to check each requirement independently.

Data Extraction Patterns (Numbers, Dates, HTML Tags)

These patterns are useful for extracting structured data from unstructured text. When working with encoded text, our String Encoder / Decoder can help you decode strings before applying regex.

Pattern 6: Integer or Decimal Number

-?\d+\.?\d*

Matches: 42, -17, 3.14, 0.5, -99.9

Matches both integers and decimal numbers, including negative values. The optional minus sign and decimal portion make it flexible.

Pattern 7: Date (YYYY-MM-DD)

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

Matches: 2026-05-11, 1999-12-31

Matches ISO 8601 date format. Validates month (01-12) and day (01-31) ranges. Does not check for impossible dates like Feb 30.

Pattern 8: Date (MM/DD/YYYY)

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

Matches: 05/11/2026, 12/25/2025

Matches US-style dates. Validates month and day ranges similarly to the ISO pattern.

Pattern 9: Time (HH:MM:SS, 24-hour)

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

Matches: 14:30:00, 00:00:00, 23:59:59

Matches 24-hour time format. Hours range from 00-23, minutes and seconds from 00-59.

Pattern 10: HTML Tags

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

Matches: <div>, </p>, <img src="..." />, <h1 class="title">

Matches opening and closing HTML tags with optional attributes. Useful for simple tag extraction, but not a replacement for a proper HTML parser for complex documents.

Pattern 11: Hex Color Code

#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})\b

Matches: #FF5733, #fff, #A1B2C3

Matches 3-digit and 6-digit hex color codes with a leading hash. Case-insensitive for the hex digits.

Pattern 12: Hashtag

#[a-zA-Z_][a-zA-Z0-9_]*

Matches: #javascript, #web_dev, #CSS3

Matches social media-style hashtags. Requires the first character after # to be a letter or underscore.

Search & Replace Patterns

These patterns are especially useful in code editors and build scripts for transforming text. The replacement uses capture groups ($1, $2) to reuse matched parts.

Pattern 13: Remove Duplicate Whitespace

Pattern
\s{2,}
Replace With

Collapses multiple consecutive whitespace characters (spaces, tabs) into a single space. Essential for cleaning user input and text processing.

Pattern 14: Trim Leading/Trailing Whitespace

Pattern
^\s+|\s+$
Replace With
(empty string)

Removes whitespace from the start and end of a string. Most languages have a built-in trim() method, but this regex works in tools that only support regex-based replacement.

Pattern 15: Convert camelCase to snake_case

Pattern
([a-z])([A-Z])
Replace With
$1_$2 (then lowercase)

Inserts an underscore between a lowercase letter followed by an uppercase letter. Apply a lowercase transformation afterward. For example, "firstName" becomes "first_name".

Pattern 16: Strip HTML Tags

Pattern
<[^>]*>
Replace With
(empty string)

Removes all HTML tags from a string, leaving only the text content. Works for simple HTML but can fail on edge cases like angle brackets in attribute values.

Here is a practical JavaScript example using search and replace with regex:

// Remove duplicate whitespace
const cleaned = "hello    world   foo".replace(/\s{2,}/g, " ");
// Result: "hello world foo"

// Convert camelCase to snake_case
const snaked = "firstName".replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
// Result: "first_name"

// Strip HTML tags
const text = "<p>Hello <b>world</b></p>".replace(/<[^>]*>/g, "");
// Result: "Hello world"

Advanced Patterns (Lookahead, Lookbehind, Groups)

These patterns use advanced regex features for more precise matching. Not all regex engines support lookbehind -- JavaScript added support in ES2018.

Pattern 17: Positive Lookahead -- Number Followed by 'px'

\d+(?=px)

Matches: The 16 in "16px", the 24 in "24px"

Matches digits only when they are followed by 'px', without including 'px' in the match. Useful for extracting numeric values from CSS.

Pattern 18: Negative Lookahead -- Word NOT Followed by a Specific Word

\bfoo(?!bar)\b

Matches: "foo" in "foo baz" but NOT in "foobar"

Matches the word 'foo' only when it is NOT followed by 'bar'. Negative lookaheads are essential for excluding specific patterns.

Pattern 19: Positive Lookbehind -- Number After '$'

(?<=\$)\d+(\.\d{2})?

Matches: 99 in "$99", 19.99 in "$19.99"

Matches a number only when preceded by a dollar sign, without including the $ in the match. Useful for extracting prices from text.

Pattern 20: Named Capture Groups

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

Matches: 2026-05-11 with named groups year, month, day

Captures parts of the match into named groups that you can reference by name instead of number. Supported in JavaScript, Python, .NET, and most modern regex engines.

Here is how named capture groups work in JavaScript:

const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = "2026-05-11".match(dateRegex);

console.log(match.groups.year);  // "2026"
console.log(match.groups.month); // "05"
console.log(match.groups.day);   // "11"

// Lookahead example: extract numbers before "px"
const css = "font-size: 16px; margin: 24px;";
const pxValues = [...css.matchAll(/(\d+)(?=px)/g)].map(m => m[1]);
console.log(pxValues); // ["16", "24"]

Frequently Asked Questions

What is the best regex for email validation?
The fully RFC 5322 compliant regex is over 6,000 characters long and impractical for production use. The pattern ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ handles 99% of real-world email addresses and is the pattern used by most web frameworks. For critical systems, combine a simple regex with a confirmation email -- that's the only way to truly verify an address exists.
How do I escape special characters in regex?
The 12 special characters that need escaping with a backslash (\) are: . * + ? ^ $ { } [ ] ( ) | \. For example, to match a literal dot use \., to match parentheses use \( and \). In JavaScript strings, backslashes themselves need escaping, so you write \\. to match a dot. When in doubt, test your pattern in a regex tester.
What is the difference between greedy and lazy matching?
Greedy quantifiers (*, +, ?) match as much text as possible. Lazy quantifiers (*?, +?, ??) match as little as possible. For the input '<b>bold</b>', the greedy pattern <.*> matches the entire string '<b>bold</b>', while the lazy pattern <.*?> matches just '<b>'. Default behavior is greedy -- add ? after the quantifier to make it lazy.
Can I use regex to parse HTML?
Regex can handle simple HTML tasks like stripping tags or finding specific elements, but it cannot reliably parse nested or complex HTML. HTML is a context-free language, not a regular language, so regex fundamentally cannot handle arbitrary nesting. Use a DOM parser instead: DOMParser in browsers, Cheerio or jsdom in Node.js, or BeautifulSoup in Python.

Test Your Regex Patterns Now

Paste any regex pattern and test string to see matches highlighted in real time. Free, private, runs in your browser.

Open Regex Tester

Related Tools