正則表達式是描述字符模式的對象,用於強大的模式匹配、搜索、替換、驗證。JavaScript 通過 RegExp 類和字符串方法支持正則。
// 1. 字面量語法(推薦,性能更好)
const regex1 = /pattern/flags;
// 2. 構造函數(動態構建模式時使用)
const regex2 = new RegExp('pattern', 'flags');
| 標志 | 名稱 | 說明 |
|---|---|---|
g | Global | 全局匹配,找到所有而非第一個 |
i | Ignore Case | 不區分大小寫 |
m | Multiline | 多行模式,^ 和 $ 匹配每行首尾 |
s | DotAll | . 匹配換行符(ES2018) |
u | Unicode | 正確處理 Unicode 代理對 |
y | Sticky | 從 lastIndex 位置開始匹配 |
[abc] // 匹配 a、b、c 中任一字符
[a-z] // 小寫字母
[0-9] // 數字
[^abc] // 非 a、b、c(取反)
. // 任意字符(除換行,除非 s 標志)
\d // 數字 [0-9]
\D // 非數字 [^0-9]
\w // 單詞字符 [a-zA-Z0-9_]
\W // 非單詞字符
\s // 空白符(空格、制表、換行)
\S // 非空白符
* // 0 或多次 {0,}
+ // 1 或多次 {1,}
? // 0 或 1 次 {0,1}
{n} // 恰好 n 次
{n,} // 至少 n 次
{n,m} // n 到 m 次
// 貪婪 vs 非貪婪
.*? // 非貪婪:盡可能少匹配
^ // 字符串/行開頭
$ // 字符串/行結尾
\b // 單詞邊界
\B // 非單詞邊界
(?=...) // 正向先行斷言
(?!...) // 負向先行斷言
(?<=...) // 正向後行斷言 (ES2018)
(?
(...) // 捕獲分組,可用 $1, $2... 或 match[1] 引用
(?:...) // 非捕獲分組,僅分組不記憶
(?...) // 命名捕獲分組 (ES2018),引用 groups.name
// test() - 返回布爾值
/abc/.test('abcde'); // true
// exec() - 返回詳細匹配信息
const re = /(\d{4})-(\d{2})/g;
let match;
while ((match = re.exec('2023-01, 2024-05')) !== null) {
console.log(match[0], match[1], match[2]); // 整個匹配、年、月
}
// match() - g 標志返回所有匹配,否則同 exec
'2023-01'.match(/(\d{4})-(\d{2})/); // ['2023-01', '2023', '01']
// replace() - 替換
'2023-01-15'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1'); // "15/01/2023"
// 函數替換
'foo bar'.replace(/\w+/g, m => m.toUpperCase()); // "FOO BAR"
// split() - 分割
'a,b;c d'.split(/[,;\s]+/); // ['a', 'b', 'c', 'd']
// search() - 返回首個匹配索引
'hello world'.search(/world/); // 6
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test('user@example.com')); // true
console.log(emailRegex.test('invalid')); // false
const phoneRegex = /^1[3-9]\d{9}$/;
console.log(phoneRegex.test('13812345678')); // true
const pwdRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;
const url = 'https://www.example.com/path?query=1';
const domain = url.match(/https?:\/\/([^\/]+)/)[1]; // "www.example.com"
/.../,避免運行時編譯(a+)+)^ $ 鎖定首尾,減少回溯const RE = /.../正則表達式雖然學習曲線陡峭,但掌握後是文本處理的利器。建議從常用模式入手,逐步深入進階語法。