← 速查表

正则语法速查表

正则表达式用来匹配文本中的模式。实际使用中九成的正则,都由下面这两打符号构成。

核心符号

符号匹配示例
.Any character except newlinea.c → abc, a1c
\d \DDigit / non-digit\d\d → 42
\w \WWord char [A-Za-z0-9_] / non-word\w+ → hello_1
\s \SWhitespace / non-whitespacea\sb → a b
^ $Start / end of string (or line with m flag)^Hi → Hi there
\bWord boundary\bcat\b → cat, not category

量词

符号含义示例
*0 or moreab*c → ac, abc, abbc
+1 or moreab+c → abc, abbc
?0 or 1 (optional)colou?r → color, colour
{n}Exactly n times\d{4} → 2026
{n,} {n,m}n or more / between n and m\d{2,4} → 12, 123, 1234
*? +? ??Lazy versions (match as little as possible)<.+?> → first tag only

分组、字符类与断言

符号含义示例
[abc] [a-z]Character class (any listed char / range)[aeiou] → vowels
[^abc]Negated class (anything but)[^0-9] → non-digits
(abc)Capturing group(\d{4})-(\d{2}) → year, month
(?:abc)Non-capturing group(?:https?|ftp)://
a|bAlternation (or)cat|dog
(?=…) (?!…)Lookahead / negative lookahead\d+(?=px) → 16 in "16px"
(?<=…) (?Lookbehind / negative lookbehind(?<=\$)\d+ → 16 in "$16"

标志位

标志含义
gGlobal — find all matches, not just the first
iCase-insensitive
m^ and $ match line starts/ends
sDot also matches newlines
uFull Unicode support

常见问题

Greedy vs lazy — when do I care?
Quantifiers are greedy by default: <.+> swallows bold whole. Add ? (<.+?>) to stop at the first closing bracket. Rule of thumb: parsing-ish tasks want lazy quantifiers.

Why does my regex match inside longer words?
You need boundaries: \bcat\b matches "cat" but not "category". Boundaries are zero-width — they assert position without consuming characters.

Can regex parse HTML?
Badly and briefly. Regex cannot track nesting; anything tree-shaped needs a real parser. Use regex for flat-text validation, extraction, and replacement.

别死记,直接用工具

Test it live in the Regex Tester