the IT Hustle
工具实战手册关于
CodeAI辅助2026-07-02•11 min 阅读

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

作者: Salty Deprecated Software Engineer

✨ AI 辅助内容

本文由 AI 辅助创作,并经团队审核以确保准确性和质量。所有技术信息和示例均已验证。

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

以 The IT Hustle 的编辑笔名写作——25 年以上笔记本维修技师、系统管理员、存储工程师和软件工程师的经验,如今用在 AI 智能体运维上。每篇文章发布前都经过人工审核,详见编辑准则。

我们的工具全部文章关于我们

获取最新资讯

第一时间了解新工具、博客文章和更新动态。无垃圾邮件。

生成专属防幻觉提示词

AI 提示词引擎采用专有技术,生成内置验证和矛盾测试的提示词。

免费试用 3 次 →

公司

  • 关于
  • 实战手册
  • AI 术语表
  • 关于作者
  • 联系我们

产品

  • 工具
  • 价格观察
  • 智能体运维
  • 编程
  • 设计
  • 运维
  • 效率
  • 营销
  • 商务

法律信息

  • 隐私政策
  • 服务条款
  • 免责声明
  • 编辑准则
  • 更正说明

© 2026 Salty Rantz LLC. 版权所有。

为在技术变革中前行的职场人打造。