Regex Cheat Sheet: Common Patterns Every Developer Needs

Published April 2026 · 10 min read

Regular expressions are one of those tools every developer encounters but few truly master. Whether you are validating form inputs, parsing log files, or performing complex search-and-replace operations, regex is indispensable. This cheat sheet covers everything from basic syntax to advanced patterns you can copy and paste into your projects today.

Want to test these patterns interactively? Try our Regex Tester tool — paste any pattern and see matches highlighted in real time.

Basic Syntax

Every regex is built from a handful of metacharacters. Understanding these is the foundation for everything else.

SymbolMeaningExample
.Any character except newlinea.c matches "abc", "a1c"
*Zero or more of precedingab*c matches "ac", "abc", "abbc"
+One or more of precedingab+c matches "abc", "abbc" but not "ac"
?Zero or one of preceding (optional)colou?r matches "color" and "colour"
^Start of string / line^Hello matches "Hello world"
$End of string / lineworld$ matches "Hello world"
[ ]Character class — match any one char inside[aeiou] matches any vowel
{n,m}Between n and m repetitionsa{2,4} matches "aa", "aaa", "aaaa"

Character Classes

Character classes are shorthand notations for commonly used sets of characters. They make your patterns much more readable than spelling out ranges manually.

ClassEquivalentDescription
\d[0-9]Any digit
\D[^0-9]Any non-digit
\w[A-Za-z0-9_]Any word character
\W[^A-Za-z0-9_]Any non-word character
\s[ \t\n\r\f\v]Any whitespace character
\S[^ \t\n\r\f\v]Any non-whitespace character
\bN/AWord boundary (zero-width)

The uppercase versions are always the negation of their lowercase counterparts. The word boundary \b is especially useful: \bcat\b matches "cat" as a whole word but not "concatenate".

Quantifiers: Greedy vs Lazy

By default, quantifiers are greedy — they match as much text as possible. Adding a ? after a quantifier makes it lazy, matching as little as possible.

.* — Greedy: matches everything it can

.*? — Lazy: matches the minimum needed

Given the string "<b>bold</b> and <b>more</b>":

<b>.*</b> matches "<b>bold</b> and <b>more</b>" (one match, greedy)

<b>.*?</b> matches "<b>bold</b>" and "<b>more</b>" (two matches, lazy)

This distinction is critical when parsing structured text. Greedy matching on nested structures is one of the most common regex bugs.

Capture Groups and Backreferences

Parentheses () create capture groups that let you extract parts of a match or reference them later in the same pattern.

(abc) — Capturing group

(?:abc) — Non-capturing group (no memory overhead)

(?<name>abc) — Named capture group

\1 — Backreference to group 1

A practical use of backreferences: detect repeated words with \b(\w+)\s+\1\b. This matches "the the" or "is is" in text. Named groups make complex patterns easier to maintain — use \k<name> to backreference a named group.

Lookahead and Lookbehind Assertions

Lookarounds assert that a pattern exists before or after the current position without consuming characters. They are zero-width, meaning they do not become part of the match.

SyntaxNameDescription
(?=...)Positive lookaheadAsserts what follows matches
(?!...)Negative lookaheadAsserts what follows does not match
(?<=...)Positive lookbehindAsserts what precedes matches
(?<!...)Negative lookbehindAsserts what precedes does not match

Example: match a number only if it is followed by "px" — \d+(?=px). In the string "12px 5em 30px", this matches "12" and "30" but not "5". Lookbehinds are especially powerful for extracting values after labels like "Price: $42" with (?<=Price:\s*)\d+.

Common Patterns Reference

Copy these battle-tested patterns into your projects. Each one is deliberately balanced between strictness and practicality.

Use CasePattern
Email^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
URLhttps?:\/\/[\w\-]+(\.[\w\-]+)+[\/\w\-.~:?#[\]@!$&'()*+,;=%]*
Phone (US)^\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
IPv4 Address^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$
Date (YYYY-MM-DD)^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Hex Color^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
HTML Tag<\/?[a-z][a-z0-9]*[^<>]*\/?>}
Strong Password^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
File Extension\.([a-zA-Z0-9]{1,10})$
Credit Card (masked)\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b

Important: email and URL patterns above are intentionally simplified for common use. The full RFC 5322 email spec is far more complex. For production validation, combine regex with server-side checks.

JavaScript-Specific Regex Tips

JavaScript provides several methods for working with regular expressions. Choosing the right one matters for correctness and performance.

RegExp.test()

/^\d+$/.test("42") // true

Returns a boolean. The fastest option when you only need to know if a pattern matches. Beware: with the g flag, test() is stateful — lastIndex advances between calls.

String.match()

"abc 123".match(/\d+/) // ["123"]

Without the g flag, returns the first match with capture groups. With g, returns an array of all matches but loses capture group info.

String.matchAll()

[..."a1 b2".matchAll(/([a-z])(\d)/g)]

Returns an iterator of all matches with full capture group information. Requires the g flag. This is almost always what you want for multi-match extraction.

String.replace() / replaceAll()

"foo bar".replace(/\b\w/g, c => c.toUpperCase()) // "Foo Bar"

The callback form is extremely powerful. Use $1, $2 in the replacement string to reference capture groups, or pass a function for dynamic replacements.

Modern JavaScript also supports the d flag (match indices), the s flag (dotAll, makes . match newlines), and the v flag (unicode sets). Use the u flag whenever working with Unicode text to ensure correct character handling.

Performance Tips: Avoiding Catastrophic Backtracking

Regex engines use backtracking to try different ways a pattern can match. Poorly written patterns can cause exponential backtracking, freezing your application for seconds or minutes on certain inputs.

Dangerous: (a+)+b — nested quantifiers on overlapping patterns cause O(2^n) time on non-matching input like "aaaaaaaaaaac".

Safe: a+b — flatten nested quantifiers when possible.

Tips to keep your regex fast:

  • Avoid nested quantifiers on patterns that can match the same characters, like (a*)*.
  • Use atomic groups or possessive quantifiers when available (not in JS, but relevant in other engines).
  • Be specific — use [^"]* instead of .* when matching content between delimiters.
  • Anchor your patterns with ^ and $ to prevent the engine from attempting matches at every position.
  • Set timeouts — in server-side code, always set a timeout or max input length when running user-supplied regex.

Real-World Examples with Explanations

1. Extract all hashtags from a tweet

/#[a-zA-Z_]\w*/g

Matches # followed by a letter or underscore, then any word characters. This excludes things like "#1" which is not a valid hashtag.

2. Convert snake_case to camelCase

str.replace(/_([a-z])/g, (_, c) => c.toUpperCase())

Captures the letter after each underscore and replaces the whole match with the uppercase version. "hello_world" becomes "helloWorld".

3. Strip HTML tags from a string

str.replace(/<[^>]*>/g, "")

Matches anything between angle brackets using the negated character class [^>]* to avoid greedy over-matching. Note: for untrusted HTML, always use a proper parser like DOMParser.

4. Validate a strong password

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

Uses four positive lookaheads to assert the presence of a lowercase letter, uppercase letter, digit, and special character without constraining their order. Then .{8,} ensures a minimum length of 8.

5. Parse a CSV line respecting quoted fields

/(?:^|,)("(?:[^"]|"")*"|[^,]*)/g

Handles both quoted and unquoted fields. Inside quotes, escaped quotes ("") are matched by [^"]|"". This covers most real-world CSV data.

Try It in DevPop

Paste any regex pattern into our free Regex Tester and see matches highlighted in real time. Supports JavaScript regex flags, capture group visualization, and match info.

Open Regex Tester