the IT Hustle
ToolsField ManualAbout
CodeAI-Assisted2026-07-02•11 min read

Regex Cheat Sheet: Every Pattern You Actually Use (With Examples)

By Salty Deprecated Software Engineer

✨ AI-Assisted Content

This article was generated with AI assistance and reviewed by our team for accuracy and quality. All technical information and examples have been verified.

Nobody memorizes regex. Even developers who use it weekly forget whether {2,} means "two or more" or "up to two", and whether lookbehind uses (?<= or (?=<. This regex cheat sheet is the page you keep open: every token you actually use, organized by job, each with a one-line explanation — followed by seven real-world recipes broken down token by token.

Everything below uses JavaScript flavor unless noted. Paste any pattern into our free regex tester to watch it match in real time — it runs entirely in your browser, so testing against real data is safe.

Character Classes

Character classes match one character from a set. They're the atoms every pattern is built from.

\dAny digit, 0–9. \D is anything that is not a digit.
\w"Word" character: letters, digits, underscore. \W is the opposite.
\sWhitespace: space, tab, newline. \S is any non-whitespace character.
.Any character except newline (unless the s flag is on).
[abc]Any one of a, b, or c. Ranges work too: [a-z], [0-9a-fA-F].
[^abc]Negation: any character that is not a, b, or c. The ^ only negates inside brackets.

Quantifiers (Greedy vs Lazy)

Quantifiers say how many times the previous token repeats. By default they're greedy — they grab as much as possible and give back only if the rest of the pattern fails.

*Zero or more. \d* matches "", "7", and "2026".
+One or more. The most common quantifier — use it when the thing must exist.
?Zero or one — makes a token optional. https? matches http and https.
{3}Exactly 3 times. {2,4} means 2 to 4; {2,} means 2 or more.
*? +? ??Lazy versions: match as little as possible. Add ? after any quantifier.

# Greedy vs lazy on: <b>bold</b> and <i>italic</i>

<.+>

→ matches the whole line (greedy grabs to the last >)

<.+?>

→ matches each tag individually (lazy stops at the first >)

Anchors

Anchors don't match characters — they match positions. Forgetting them is the number one cause of validation patterns that accept garbage.

^Start of the string (or start of a line with the m flag).
$End of the string (or end of a line with the m flag).
\bWord boundary — the edge between a \w character and a non-word character. \bcat\b matches "cat" but not "concatenate".

Groups & Backreferences

(abc)Capture group — matches "abc" and remembers it as group 1, usable as $1 in replacements.
(?:abc)Non-capture group — groups for quantifiers or alternation without saving anything. Slightly faster, keeps group numbers clean.
(?<name>abc)Named group — read it as match.groups.name instead of a mystery index.
\1Backreference — matches whatever group 1 captured. (['"]).*?\1 matches a quoted string closed by the same quote it opened with.
a|bAlternation — a or b. Scope it with a group: gr(a|e)y matches gray and grey.

Lookarounds

Lookarounds check what's next to the match position without consuming it. They're how you say "match X, but only when Y is nearby".

(?=...)Lookahead — the following text must match, but isn't part of the result.
(?!...)Negative lookahead — the following text must not match.
(?<=...)Lookbehind — the preceding text must match.
(?<!...)Negative lookbehind — the preceding text must not match.

# Lookahead: password must contain a digit (checked, not consumed)

^(?=.*\d).{8,}$

# Lookbehind: grab the number after "total: " without capturing the label

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

Flags

gGlobal — find all matches, not just the first. Without it, replace only touches one occurrence.
iCase-insensitive — /error/i matches ERROR, Error, and error.
mMultiline — ^ and $ match at every line break, not just string edges. Essential for logs.
sDot-all — makes . also match newlines, so one pattern can span lines.
uUnicode — correct handling of emoji and non-Latin scripts, and enables \p{L} property classes.

Escaping Special Characters

These characters have special meaning and need a backslash to be matched literally: . * + ? ^ $ ( ) [ ] { } | \ /. So a literal dot is \., a literal plus is \+, and a literal backslash is \\. Inside a character class most of them lose their powers — [.+?] matches a literal dot, plus, or question mark. When in doubt, escape it and test the pattern live — an unescaped dot matching everything is one of the sneakiest regex bugs there is.

Recipes: Real Patterns, Token by Token

The tokens above are the vocabulary. Here's how they combine into the seven patterns developers reach for most.

1. Email (deliberately loose)

^[^\s@]+@[^\s@]+\.[^\s@]+$

[^\s@]+ means "one or more characters that aren't whitespace or @" — that's the local part. Then a literal @, the same class again for the domain, an escaped dot, and one more run for the TLD. Anchored on both ends so "hello user@example.com bye" doesn't pass. It catches real typos without pretending to be an RFC parser — more on why below.

2. URL (http/https)

https?:\/\/[\w.-]+(?:\/[^\s]*)?

https? makes the s optional. :\/\/ is a literal ://. [\w.-]+ matches the host — word characters, dots, and hyphens. The final (?:\/[^\s]*)? is an optional non-capture group: a slash followed by anything that isn't whitespace, so paths and query strings ride along. Great for extracting URLs from text; for validating one, use your language's URL parser instead.

3. Date, YYYY-MM-DD

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

\d{4} is exactly four digits for the year. The month group uses alternation: 0[1-9] covers 01–09, 1[0-2] covers 10–12 — so month 13 fails. The day group does the same for 01–31. Regex can't know February has 28 days; this pattern filters the format, and your date library validates the calendar.

4. Extracting values from logs

status=(?<code>\d{3}) duration=(?<ms>\d+)ms

# Matches:

GET /api/users status=500 duration=1204ms

Two named groups: (?<code>\d{3}) captures exactly three digits after the literal text status=, and (?<ms>\d+) grabs the duration before the literal ms. Anchoring to literal labels like status= is the trick — you match the structure of the line, then capture only the variable parts.

5. Quoted strings

(["'])(.*?)\1

Group 1 captures the opening quote — double or single. (.*?) lazily captures the contents, stopping at the first chance to close. The backreference \1 demands the same quote character that opened the string, so "it's fine" matches as one string instead of breaking at the apostrophe. The lazy quantifier matters: greedy (.*) would swallow everything between the first and last quote on the line.

6. Trimming whitespace

Find (with g + m flags):

^\s+|\s+$

Replace with:

(empty string)

Alternation between two anchored runs: ^\s+ is whitespace glued to the start of a line, \s+$ is whitespace glued to the end. With the m flag it trims every line in a file at once — the classic cleanup for copy-pasted data.

7. Semantic version (semver)

^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?$

Three captured digit runs separated by escaped dots — major, minor, patch — so 2.14.0 yields groups 1–3 you can compare numerically. The tail (?:-([\w.-]+))? is an optional non-capture group holding a capture group: if a pre-release tag like -beta.1 exists, group 4 gets beta.1 without the hyphen. A nice example of mixing capture and non-capture groups deliberately.

Common Mistakes

Catastrophic backtracking. Nested quantifiers like (a+)+$ can make the engine try exponentially many ways to split the input before failing — a 30-character non-matching string can hang a server. Avoid quantifying a group whose contents are themselves quantified, and keep inner classes mutually exclusive.
Over-validating emails. Strict email regexes reject real addresses (plus-tags, new TLDs, unicode domains) while still admitting fakes. Validate loosely, then send a confirmation email — that's the only real test.
Forgetting anchors. \d{4} happily matches inside "abc12345xyz". If you mean "the whole input is a four-digit number", you must write ^\d{4}$. Unanchored validation is how "123abc" ends up in your database as an age.
Assuming one flavor. JavaScript, PCRE, Python, and Go all differ: lookbehind support varies, \d matches non-ASCII digits in some engines, and Go's RE2 has no backreferences at all. Test in the flavor your code actually runs — a pattern copied from a PHP answer on Stack Overflow may not behave the same in Node.

Keep This Loop: Write, Test, Ship

A cheat sheet gets you 90% of the way; the last 10% is watching the pattern run against real data. Keep this page open in one tab and the regex tester in another — it highlights matches on every keystroke, shows what each capture group grabbed, and previews replacements, all without your data ever leaving the browser. If you want more tooling options, we compared the best free regex testers in a separate post. And if you're wondering whether any of this is worth learning when AI can generate patterns on demand — it is, precisely because someone has to verify what the AI wrote. We made that case in why regex is still worth learning in the age of AI.

IT
Salty Deprecated Software Engineer

Written under The IT Hustle's editorial pen name — 25+ years as a laptop technician, system administrator, storage engineer, and software engineer, now operating AI agents. Every post is reviewed by a human before it ships; see the editorial policy for how this site is made.

Our ToolsAll ArticlesAbout Us

Stay in the Loop

Be the first to know about new tools, blog posts, and updates. No spam.

Generate Your Own Anti-Hallucination Prompts

Our AI Prompt Engine uses proprietary technology to generate prompts with built-in verification and contradiction testing.

Try 3 Free Generations →

Company

  • About
  • Field Manual
  • AI Glossary
  • The Author
  • Contact

Product

  • Tools
  • Agent Ops
  • Code
  • Design
  • Sysadmin
  • Productivity
  • Marketing
  • Business

Legal

  • Privacy Policy
  • Terms of Service
  • Disclaimer
  • Editorial Policy
  • Corrections

© 2026 Salty Rantz LLC. All rights reserved.

Made for workers navigating tech upheaval.