正規表示式備忘錄

正規語法速查與常用模式參考,涵蓋字元類、量詞、錨點、斷言等。 完全免費、免註冊、瀏覽器本機處理,不上傳伺服器。

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點擊複製