| 標誌 | 名稱 | 說明 |
g | Global | 全域匹配,找到所有而非第一個 |
i | Ignore Case | 忽略大小寫 |
m | Multiline | ^ $ 匹配行首行尾 |
s | DotAll (ES2018) | . 匹配換行符 |
u | Unicode (ES2015) | 正確處理 Unicode 代理對、屬性轉義 |
y | Sticky (ES2015) | 從 lastIndex 位置開始匹配,不向後嘗試 |
核心方法
RegExp 實例方法
const regex = /\d+/g;
const str = "2024年1月15日";
// test() - 布林值,常用於 if 判斷
regex.test(str); // true (會改變 lastIndex)
// exec() - 返回詳細匹配資訊陣列,或 null
regex.exec(str); // ["2024", index: 0, input: "...", groups: undefined]
// 循環獲取所有匹配
let match;
while ((match = regex.exec(str)) !== null) {
console.log(match[0], match.index);
}
// 字串方法 (更常用)
// match() - g 旗標下返回所有匹配陣列,無 g 返回首個匹配詳情
str.match(/\d+/g); // ["2024", "1", "15"]
// matchAll() (ES2020) - 返回迭代器,含分組資訊
[...str.matchAll(/(\d+)(年|月|日)/g)];
// 每項: ["2024年", "2024", "年", index: 0, ...]
// search() - 返回首個匹配索引,無匹配 -1
str.search(/\d+/); // 0
// replace() - 替換
str.replace(/\d+/g, 'X'); // "X年X月X日"
str.replace(/(\d+)年/, '$1-'); // "2024-1月15日" ($1 為第一分組)
// split() - 分割
"a,b;c".split(/[,;]/); // ["a", "b", "c"]
常用模式速查表
| 需求 | 正則 | 說明 |
| Email | /^[^\s@]+@[^\s@]+\.[^\s@]+$/ | 簡易版,嚴格驗證極複雜 |
| 手機號 (中國) | /^1[3-9]\d{9}$/ | 11位,首位1,第二位3-9 |
| 身份證 (18位) | /^\d{17}[\dXx]$/ | 僅格式,校驗碼需算法 |
| URL | /^https?:\/\/[^\s/$.?#].[^\s]*$/i | 簡易版 |
| IPv4 | /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/ | 精確匹配 |
| 中文字符 | /[\u4e00-\u9fa5]/ | 基本漢字區 |
| 去除首尾空白 | /^\s+|\s+$/g | str.trim() 更好 |
| 千分位分隔 | /\B(?=(\d{3})+(?!\d))/g | 替換為 ',' |
| HTML 標籤 | /<[^>]*>/g | 簡易移除標籤 |
| 日期 YYYY-MM-DD | /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/ | 格式驗證,邏輯驗證需額外判斷 |
進階技巧
1. 分組與反向引用
// 捕獲分組 ()
/(\d{4})-(\d{2})-(\d{2})/.exec('2024-01-15');
// ["2024-01-15", "2024", "01", "15"]
// 命名分組 (ES2018)
/(?\d{4})-(?\d{2})-(?\d{2})/.exec('2024-01-15').groups
// {year: "2024", month: "01", day: "15"}
// 反向引用 \1 \k
/(['"])(.*?)\1/.exec('"hello"'); // ["\"hello\"", "\"", "hello"]
/(?['"])(.*?)\k/.exec("'world'"); // ["'world'", "'", "world"]
// 替換中使用 $1 $
'2024-01-15'.replace(/(?\d{4})-(?\d{2})-(?\d{2})/, '$/$/$');
// "01/15/2024"
2. 斷言 (零寬斷言)
| 類型 | 語法 | 含義 | 例子 |
| 正向先行 | (?=...) | 後面必須匹配... | \d+(?=px) 匹配 "100px" 中的 "100" |
| 負向先行 | (?!...) | 後面不能匹配... | \d+(?!px) 匹配非 px 後的數字 |
| 正向後行 | (?<=...) | 前面必須匹配... (ES2018) | (?<=\$)\d+ 匹配 "$100" 中的 "100" |
| 負向後行 | (? | 前面不能匹配... (ES2018) | (? 匹配非 $ 開頭的數字 |
3. 貪婪 vs 惰性量詞
const str = '內容1
內容2
';
// 貪婪 (預設) - 匹配盡可能多
str.match(/.*<\/div>/); // ["
內容1
內容2
"]
// 惰性 - 匹配盡可能少
str.match(/
.*?<\/div>/g); // ["
內容1
", "
內容2
"]
效能優化原則
- 避免災難性回溯:
(a+)+、(a|a?)+ 遇到長字串 aaaaaaaaaaaaa! 會指數級回溯。使用佔有優先量詞 (?>a+) 或原子分組 (JS 不支援,需改寫)。
- 錨點優化:
^pattern$ 限定開頭結尾,避免全字串掃描。
- 具體字符類別:
[abc] 優於 .,\d 優於 [0-9] (語義清晰)。
- 預編譯複用:全域常量儲存 RegExp,避免循環中重複建構。
- 避免過度捕獲:非必要不用
(),用 (?:...) 非捕獲分組。
實戰:表單驗證工具類
const Validators = {
patterns: {
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
phone: /^1[3-9]\d{9}$/,
idCard: /^\d{17}[\dXx]$/,
password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/, // 大小寫+數字 8位以上
chinese: /^[\u4e00-\u9fa5]+$/,
url: /^https?:\/\/[^\s/$.?#].[^\s]*$/i
},
validate(type, value) {
const regex = this.patterns[type];
if (!regex) return { valid: false, message: '未知驗證類型' };
return { valid: regex.test(value), message: regex.test(value) ? '' : `格式不正確` };
},
// 批次驗證
validateForm(rules) {
const errors = {};
for (const [field, {type, value, required=true}] of Object.entries(rules)) {
if (required && !value) {
errors[field] = '必填';
} else if (value) {
const {valid, message} = this.validate(type, value);
if (!valid) errors[field] = message;
}
}
return Object.keys(errors).length ? errors : null;
}
};
// 使用
const errors = Validators.validateForm({
email: {type: 'email', value: 'test@example.com'},
phone: {type: 'phone', value: '13800138000'},
pwd: {type: 'password', value: 'Abc12345'}
});
除錯工具
- Regex101:視覺化解釋、步驟執行、效能分析 (支援 JS/PCRE/Python/Golang)
- Regexper:鐵軌圖視覺化
- 瀏覽器 DevTools Console 直接測試
總結
JavaScript 正則表達式透過 RegExp 物件與字串方法 (match, replace, split) 強大支援文本處理。掌握分組/反向引用、斷言、惰性量詞、Unicode 模式等進階特性,配合效能優化原則避免回溯災難,能高效解決驗證、解析、轉換等需求。現代開發優先使用 matchAll、命名分組、URLSearchParams 等新 API 提升可讀性與維護性。
copyright ©
萬盛學電腦網 all rights reserved