正则表达式备忘录

正则语法速查与常用模式参考,涵盖字符类、量词、锚点、断言等。 完全免费、免注册、浏览器本地处理,不上传服务器。

Character Classes

[abc]Any of a, b, or c/[aeiou]/.test('a') → true点击复制
[^abc]Not a, b, nor c/[^aeiou]/.test('b') → true点击复制
[a-z]Character range a to z/[a-z]/.test('m') → true点击复制
.Any character except newline/./.test('x') → true点击复制
\dDigit [0-9]/\d/.test('5') → true点击复制
\DNon-digit [^0-9]/\D/.test('a') → true点击复制
\wWord character [a-zA-Z0-9_]/\w/.test('_') → true点击复制
\WNon-word character/\W/.test('!') → true点击复制
\sWhitespace/\s/.test(' ') → true点击复制
\SNon-whitespace/\S/.test('a') → true点击复制

Quantifiers

*0 or more/go*/.test('g') → true点击复制
+1 or more/go+/.test('go') → true点击复制
?0 or 1 (optional)/colou?r/.test('color') → true点击复制
{n}Exactly n/a{3}/.test('aaa') → true点击复制
{n,}n or more/a{2,}/.test('aaa') → true点击复制
{n,m}Between n and m/a{2,4}/.test('aaa') → true点击复制
*?0 or more (lazy)/a*?/.exec('aaa') → ''点击复制
+?1 or more (lazy)/a+?/.exec('aaa') → 'a'点击复制

Anchors

^Start of string/^hello/.test('hello world') → true点击复制
$End of string/world$/.test('hello world') → true点击复制
\bWord boundary/\bword\b/.test('a word b') → true点击复制
\BNon-word boundary/\Bord\B/.test('word') → false点击复制

Groups & Capturing

(abc)Capture group/(ab)c/.exec('abc')[1] → 'ab'点击复制
(?:abc)Non-capturing group/(?:ab)c/.exec('abc')[1] → undefined点击复制
(?<name>abc)Named capture group/(?<w>ab)c/.exec('abc').groups.w → 'ab'点击复制
\1Backreference to group 1/(a)\1/.test('aa') → true点击复制
$1Replacement reference'ab'.replace(/(a)/, '$1x') → 'axb'点击复制

Lookaround Assertions

(?=abc)Positive lookahead/a(?=b)/.test('ab') → true点击复制
(?!abc)Negative lookahead/a(?!b)/.test('ac') → true点击复制
(?<=abc)Positive lookbehind/(?<=a)b/.test('ab') → true点击复制
(?<!abc)Negative lookbehind/(?<!a)b/.test('cb') → true点击复制

Flags

gGlobal — find all matches'aaa'.replace(/a/g, 'b') → 'bbb'点击复制
iCase-insensitive/a/i.test('A') → true点击复制
mMultiline (^/$ match line ends)/^b/m.test('a\nb') → true点击复制
sDotall (. matches newline)/a.b/s.test('a\nb') → true点击复制
uUnicode/\u{1F600}/u.test('😀') → true点击复制
ySticky (match at lastIndex)/a/y.exec('aaa') → 'a' at 0点击复制

Common Patterns

^[\w.-]+@[\w.-]+\.\w+$Email (basic)/^[\w.-]+@[\w.-]+\.\w+$/.test('a@b.com') → true点击复制
^https?://[\S]+$URL (basic)/^https?:\/\/[\S]+$/.test('http://x') → true点击复制
^\d{4}-\d{2}-\d{2}$Date YYYY-MM-DD/^\d{4}-\d{2}-\d{2}$/.test('2024-01-01') → true点击复制
^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$Hex color/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test('#fff') → true点击复制
^\d+$Integer only/^\d+$/.test('123') → true点击复制
^-?\d+(\.\d+)?$Decimal number/^-?\d+(\.\d+)?$/.test('-3.14') → true点击复制
^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$Strong password (8+ chars, upper, lower, digit)test('Abc12345') → true点击复制