字符类
模式
描述
示例
.
匹配除换行符外的任意字符
a.c → "abc", "a1c"
\w
单词字符 [a-zA-Z0-9_]
\w+ → "hello", "foo_bar"
\W
非单词字符
\W → " ", "!"
\d
数字字符 [0-9]
\d+ → "123", "42"
\D
非数字字符
\D+ → "abc", "hello"
\s
空白字符(空格、制表符、换行等)
a\sb → "a b", "a\tb"
\S
非空白字符
\S+ → "hello", "world"
[abc]
字符集,匹配 a、b 或 c
[aeiou] → "a", "e"
[^abc]
否定字符集,匹配除 a、b、c 外的字符
[^0-9] → "a", "b"
[a-z]
字符范围,匹配 a 到 z
[a-z]+ → "hello"
[a-zA-Z]
匹配所有字母
[a-zA-Z]+ → "Hello"
锚点
模式
描述
示例
^
匹配字符串(或行)开头
^Hello → "Hello world"
$
匹配字符串(或行)结尾
world$ → "Hello world"
\b
单词边界
\bcat\b → "cat", not "cats"
\B
非单词边界
\Bcat → "scat"
\A
字符串绝对开头
\AHello → "Hello world"
\Z
字符串绝对结尾
world\Z → "Hello world"
量词
模式
描述
示例
*
匹配 0 次或多次(贪婪)
ab*c → "ac", "abc", "abbc"
+
匹配 1 次或多次(贪婪)
ab+c → "abc", "abbc"
?
匹配 0 次或 1 次(可选)
colou?r → "color", "colour"
{n}
精确匹配 n 次
a{3} → "aaa"
{n,}
至少匹配 n 次
a{2,} → "aa", "aaa"
{n,m}
匹配 n 到 m 次
a{2,4} → "aa", "aaa", "aaaa"
*?
懒惰匹配(非贪婪),尽量少匹配
<.*?> → "<a>" (not "<a>...</a>")
+?
懒惰匹配 1 次或多次
a+? → "a" in "aaa"
分组
模式
描述
示例
(abc)
捕获组,匹配并捕获内容
(foo)bar → 捕获 "foo"
(?:abc)
非捕获组,仅匹配不捕获
(?:foo|bar)baz
(?<name>abc)
命名捕获组
(?<year>\d{4})
|
或,匹配左边或右边
cat|dog → "cat" 或 "dog"
\1
反向引用第 1 个捕获组
(\w+)\s\1 → "hello hello"
\k<name>
命名反向引用
(?<w>\w+)\s\k<w>
标志
模式
描述
示例
g
全局匹配,查找所有匹配项
/\d+/g → 所有数字
i
忽略大小写
/hello/i → "Hello", "HELLO"
m
多行模式,^ 和 $ 匹配每行
/^foo/m → 每行开头的 foo
s
dotAll 模式,. 匹配换行符
/a.b/s → "a\nb"
u
Unicode 模式,正确处理 Unicode
/\u{1F600}/u
y
粘性模式,从 lastIndex 位置匹配
/\d+/y
d
返回匹配项的索引范围
/foo/d
先行/后行断言
模式
描述
示例
(?=abc)
正向先行断言,后面必须跟着 abc
foo(?=bar) → "foo" in "foobar"
(?!abc)
负向先行断言,后面不能跟着 abc
foo(?!bar) → "foo" in "foobaz"
(?<=abc)
正向后行断言,前面必须是 abc
(?<=foo)bar → "bar" in "foobar"
(?<!abc)
负向后行断言,前面不能是 abc
(?<!foo)bar → "bar" in "bazbar"
About this tool
Complete regex syntax cheat sheet covering character classes, anchors, quantifiers, groups, modifiers, and lookaheads/lookbehinds. Searchable and filterable for quick reference.
regex正则cheatsheet速查regexp语法