正則表達式是字串處理、表單驗證、資料萃取的利器。本文整理前端開發最常用的正則模式,並說明 JavaScript 專屬用法與效能優化技巧。
| 用途 | 正則模式 | 說明 |
|---|---|---|
| 中文字元 | [\u4e00-\u9fa5] | 基本漢字區段(CJK Unified Ideographs) |
| 雙位元組字元 | [^\x00-\xff] | 含中文、全形符號,可用於計算「視覺長度」 |
/^[\w.-]+@[\w-]+(\.[\w-]+)+$/ | 實務建議:type="email" + 後端再驗證 | |
| URL | /^https?:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/ | 支援 http/https、子網域、路徑、查詢字串 |
| 手機號碼 (TW) | /^09\d{8}$/ | 台灣手機 09 開頭 10 碼 |
| 身分證字號 (TW) | /^[A-Z][12]\d{8}$/ | 首字母 + 性別碼 + 8 碼數字 |
| 郵遞區號 (TW) | /^\d{3}(\d{2})?$/ | 3 碼或 5 碼 |
| IPv4 | /^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/ | 嚴格驗證 0-255 各段 |
| 日期 (YYYY-MM-DD) | /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/ | 格式驗證,實際日期有效性需額外判斷 |
| 中文姓名 | ^[\u4e00-\u9fa5]{2,10}$ | 2-10 個中文字 |
| 使用者帳號 | /^[a-zA-Z0-9_]{4,16}$/ | 英數底線 4-16 碼 |
| 強密碼 | /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/ | 大小寫、數字、特殊符號各至少 1,8 碼以上 |
String.prototype.visualLength = function() {
return this.replace(/[^\x00-\xff]/g, 'aa').length;
};
// 使用
'中文abc'.visualLength(); // 8
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
// 現代瀏覽器原生支援 String.prototype.trim()
function ipToNumber(ip) {
const match = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if (!match) throw new Error('Invalid IP');
return (+match[1] << 24) + (+match[2] << 16) + (+match[3] << 8) + (+match[4]);
}
// 或使用 split 更簡潔
function ipToNumberSimple(ip) {
return ip.split('.').reduce((acc, octet) => (acc << 8) + +octet, 0) >>> 0;
}
function getFileNameFromUrl(url) {
return url.replace(/^.*\/([^/?#]+)(\?.*)?(#.*)?$/, '$1');
}
// 範例
getFileNameFromUrl('https://example.com/path/file.name.jpg?ver=1#anchor'); // 'file.name.jpg'
<!-- 僅中文 -->
<input oninput="value=value.replace(/[^\u4e00-\u9fa5]/g, '')">
<!-- 僅全形 -->
<input oninput="value=value.replace(/[^\uff00-\uffff]/g, '')">
<!-- 僅數字 -->
<input oninput="value=value.replace(/\D/g, '')">
<!-- 數字+英文 -->
<input oninput="value=value.replace(/[^a-zA-Z0-9]/g, '')">
g 全域比對i 不區分大小寫m 多行模式(^$ 匹配行首尾)s (ES2018) . 匹配換行符u (ES2015) Unicode 模式,正確處理 Emoji、擴展漢字y (ES2015) Sticky 模式,從 lastIndex 開始匹配// 捕獲分組
/(\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/.exec('"hello"'); // [""hello"", "", "hello"]
// \1 參考第一個捕獲組(引號),確保前後引號一致
// 正向先行斷言:匹配後面是數字的字母
/[a-z]+(?=\d)/.exec('abc123'); // ['abc']
// 負向先行斷言:匹配後面非數字的字母
/[a-z]+(?!\d)/.exec('abc!'); // ['abc']
// 正向後行斷言 (ES2018):匹配前面是 $ 的數字
/(?<=\$)\d+/.exec('$100'); // ['100']
// 負向後行斷言 (ES2018):匹配前面非 $ 的數字
/(?
(a+)+、(a*)*,使用佔有優先量詞 (?>a+) 或原子分組^,減少掃描位置[\w-] 好過 .、\Sconst re = /pattern/,避免重複編譯test() 比 exec()、match() 快(只需布林值時)function uniqueChars(str) {
return [...new Set(str)].join('');
}
// 或用正則(不保證順序)
function uniqueCharsRegex(str) {
return str.replace(/(.)(?=.*\1)/g, '');
}
善用正則表達式能大幅簡化字串處理邏輯,但複雜解析(HTML、JSON、程式碼)請改用專用 Parser,避免陷入正則地獄。