基本驗證類
| 名稱 | 正則 | 測試範例 |
| 用戶名 | /^[a-z0-9_-]{3,16}$/i | user_1, JohnDoe |
| 密碼(強) | /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/ | Pass123! |
| 密碼(中等) | /^(?=.*\d)(?=.*[a-zA-Z]).{6,18}$/ | abc123 |
| Email | /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i | test@example.com |
| 手機(大陸) | /^1[3-9]\d{9}$/ | 13800138000 |
| 手機(台灣) | /^09\d{8}$/ | 0912345678 |
| 身分證(台灣) | /^[A-Z][12]\d{8}$/ | A123456789 |
| 統一編號 | /^\d{8}$/ | 12345678 |
| 郵遞區號(台灣) | /^\d{3}(\d{2})?$/ | 100, 10045 |
| URL | /^https?:\/\/[^\s/$.?#].[^\s]*$/i | https://example.com/path |
| IPv4 | /^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/ | 192.168.1.1 |
| 十六進位色碼 | /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i | #ff0000, #f00 |
| 日期 | /^\d{4}-\d{2}-\d{2}$/ | 2024-12-25(格式檢查) |
| 中文 | /^[\u4e00-\u9fa5]+$/ | 測試文字 |
| 中英數底線 | /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/ | 測試_test123 |
數字相關
| 類型 | 正則 |
| 非負整數 | /^\d+$/ |
| 正整數 | /^[1-9]\d*$/ |
| 負整數 | /^-[1-9]\d*$/ |
| 整數 | /^-?[1-9]\d*|0$/ |
| 非負浮點數 | /^\d+(\.\d+)?$/ |
| 正浮點數 | /^([1-9]\d*|0)(\.\d+)?$/ |
| 浮點數 | /^-?([1-9]\d*|0)(\.\d+)?$/ |
| 金額(2 位小數) | /^\d+(\.\d{1,2})?$/ |
字串處理常用模式
// 1. 千分位分隔
'1234567.89'.replace(/\B(?=(\d{3})+(?!\d))/g, ','); // "1,234,567.89"
// 2. 去除首尾空白
str.replace(/^\s+|\s+$/g, '');
// 或 ES2019: str.trim()
// 3. 去除所有空白
str.replace(/\s+/g, '')
// 4. 去除 HTML 標籤
str.replace(/<[^>]*>/g, '')
// 5. 匹配 HTML 標籤(含屬性、巢狀不支援)
/<([a-z]+)([^<]*)>(.*?)<\/\1>/gis
// 6. 驗證不含連續重複字元
/^(?!.*(.)\1{2,})/
// 7. 匹配中文標點
/[\u3000-\u303f\uff00-\uffef]/
// 8. 匹配 Emoji(簡易)
/[\u{1F600}-\u{1F64F}]/u
進階技巧
命名捕獲組 (ES2018)
const re = /(?\d{4})-(?\d{2})-(?\d{2})/;
const match = '2024-12-25'.match(re);
console.log(match.groups); // {year: "2024", month: "12", day: "25"}
先行/後行斷言
// 正向先行斷言:匹配後面是 "px" 的數字
/\d+(?=px)/.exec('16px'); // ["16"]
// 負向先行斷言:匹配後面不是 "px" 的數字
/\d+(?!px)/.exec('16em'); // ["16"]
// 正向後行斷言:匹配前面是 "$" 的數字
/(?<=\$)\d+/.exec('$100'); // ["100"]
// 負向後行斷言:匹配前面不是 "$" 的數字
/(?
JS 正則常用方法速查
| 方法 | 用途 | 回傳 |
regex.test(str) | 布林檢測 | true/false |
str.match(regex) | 匹配詳情 | Array/null(含 groups, index) |
str.matchAll(regex) | 所有匹配迭代器 | Iterator(需 g 旗標) |
str.search(regex) | 首個匹配索引 | number/-1 |
str.replace(regex, repl) | 替換 | 新字串 |
str.replaceAll(str/regex, repl) | 全域替換 | 新字串 |
str.split(regex) | 分割 | Array |
regex.exec(str) | 單次匹配(可迭代) | Array/null |
效能與安全提醒
- 避免災難性回溯:
(a+)+, (.*)* → 改用具體字元類 [^"]*
- 長字串用
split 而非 matchAll
- 複用
RegExp 物件,避免迴圈中 new RegExp()
- 使用者輸入正則需嚴格限制或用
escapeRegExp 轉義
- ReDoS 風險:不可信正則勿直接用於生產環境
線上測試工具推薦
- Regex101 (https://regex101.com) - 解釋、除錯、效能分析
- RegExr (https://regexr.com) - 視覺化、社群庫
- Debuggex (https://www.debuggex.com) - 圖形化鐵道圖