一、正則表達式定義方式
1. 字面量語法 (Literal) - 推薦
// 格式:/pattern/flags
var re1 = /^\d+$/; // 純數字
var re2 = /^[a-zA-Z0-9_]+$/; // 英數字底線
var re3 = /abc/i; // 不分大小寫
var re4 = /test/g; // 全域匹配
var re5 = /^test$/m; // 多行模式
2. 建構函式語法 (Constructor)
// 格式:new RegExp(pattern[, flags])
var re1 = new RegExp("^\\d+$"); // 需雙重轉義 \\
var re2 = new RegExp("^[a-zA-Z0-9_]+$");
var re3 = new RegExp("abc", "i");
var re4 = new RegExp("test", "g");
// 動態建構正則 (字面量無法做到)
var keyword = "user";
var dynamicRe = new RegExp("^" + keyword + "\\d+$", "i");
兩者差異對照
| 特性 | 字面量 /.../ | 建構函式 new RegExp() |
| 編譯時機 | 腳本載入時編譯一次 | 執行時每次新建編譯 |
| 效能 | 較好 (靜態模式) | 較差 (動態模式) |
| 轉義處理 | 單層轉義 | 雙層轉義 (字串 + 正則) |
| 動態模式 | 不支援 | 支援變數插值 |
| 可讀性 | 較佳 | 較差 |
二、三大核心驗證方法
1. RegExp.prototype.test(str) - 僅判斷是否匹配
var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var isValid = emailRe.test("user@example.com"); // true
var isValid2 = emailRe.test("invalid-email"); // false
// 適用場景:表單驗證、條件判斷、特徵檢測
if (/^https?:\/\//.test(url)) { ... }
2. RegExp.prototype.exec(str) - 獲取匹配詳情
var re = /(\d{4})-(\d{2})-(\d{2})/;
var str = "今天是 2024-01-15";
var match = re.exec(str);
if (match) {
console.log(match[0]); // "2024-01-15" (完整匹配)
console.log(match[1]); // "2024" (第 1 組)
console.log(match[2]); // "01" (第 2 組)
console.log(match[3]); // "15" (第 3 組)
console.log(match.index); // 3 (匹配位置)
console.log(match.input); // 原字串
}
// 全域模式下可迭代所有匹配
var globalRe = /\d+/g;
var str = "ID: 123, 年齡: 25, 分數: 98";
var match;
while ((match = globalRe.exec(str)) !== null) {
console.log("找到數字:", match[0], "位置:", match.index);
}
3. String.prototype.match(re) - 字串方法,返回匹配陣列
var str = "index.aspx?test=1&ww=2&www=3";
var re = /(\w+)=(\d+)/g;
// 有 g 旗標:返回所有完整匹配 (不含分組)
var matches = str.match(re);
console.log(matches); // ["test=1", "ww=2", "www=3"]
// 無 g 旗標:等同 exec,返回第一個匹配詳情
var re2 = /(\w+)=(\d+)/;
var match = str.match(re2);
console.log(match[0]); // "test=1"
console.log(match[1]); // "test"
console.log(match[2]); // "1"
三、其他實用字串方法
String.prototype.replace(re, replacement)
// 字串替換
"hello world".replace(/world/, "JS"); // "hello JS"
"2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1"); // "01/15/2024"
// 函式替換 (動態計算)
"價格: $100".replace(/\$(\d+)/, function(match, num) {
return "$" + (parseInt(num) * 1.05).toFixed(2); // 加 5% 稅
}); // "價格: $105.00"
// 全域替換需加 g 旗標
"a b c".replace(/ /g, "-"); // "a-b-c"
String.prototype.split(re)
// 正則分割
"a,b;c|d".split(/[,;|]/); // ["a", "b", "c", "d"]
" a b c ".split(/\s+/); // ["a", "b", "c"] (多空白視為一個分隔)
"abc".split(/(b)/); // ["a", "b", "c"] (保留分隔符)
String.prototype.search(re)
// 返回第一個匹配位置,找不到返回 -1
"hello world".search(/world/); // 6
"hello".search(/world/); // -1
四、常用驗證正則模式庫
基礎驗證
// 中文
/^[\u4e00-\u9fa5]+$/
// 英文字母
/^[a-zA-Z]+$/
// 英數字
/^[a-zA-Z0-9]+$/
// 英數字底線 (常用於用戶名)
/^[a-zA-Z0-9_]{4,16}$/
// 整數
/^-?\d+$/
// 正整數
/^[1-9]\d*$/
// 浮點數 (含負數)
/^-?\d+(\.\d+)?$/
// 金額 (兩位小數)
/^\d+(\.\d{1,2})?$/
格式驗證
// Email (簡易版)
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
// Email (RFC 5322 簡化版)
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
// 手機號 (台灣)
/^09\d{8}$/
// 手機號 (中國大陸)
/^1[3-9]\d{9}$/
// 身分證字號 (台灣)
/^[A-Z][12]\d{8}$/
// 統一編號 (台灣)
/^\d{8}$/
// URL
/^https?:\/\/[^\s/$.?#].[^\s]*$/i
// IP 地址 (IPv4)
/^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
// 日期 YYYY-MM-DD
/^\d{4}-\d{2}-\d{2}$/
// 密碼 (8-16 位,含大小寫數字特殊字元)
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,16}$/
五、轉義字元完整表
| 字元 | 含義 | 匹配字面字元需轉義 |
\ | 轉義字元 | \\ |
^ | 行首 | \^ |
$ | 行尾 | \$ |
. | 任意字元 (除換行) | \. |
* | 零或多次 | \* |
+ | 一次或多次 | \+ |
? | 零或一次 / 非貪婪 | \? |
{} | 量詞範圍 | \{ \} |
() | 分組/捕獲 | \( \) |
[] | 字元類別 | \[ \] |
| | 或運算 | \| |
/ | 字面量分隔符 | \/ (僅字面量需轉義) |
特殊字元類別速查
\d = [0-9] 數字
\D = [^0-9] 非數字
\w = [a-zA-Z0-9_] 單字字元 (英數字底線)
\W = [^a-zA-Z0-9_] 非單字字元
\s = [\t\n\r\f\v ] 空白字元
\S = [^\t\n\r\f\v ] 非空白字元
. = [^\n] 任意字元 (除換行)
[\s\S] 真正任意字元 (含換行)
六、實務範例:表單驗證工具
var Validator = {
patterns: {
required: /.+/,
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
phone: /^09\d{8}$/,
idCard: /^[A-Z][12]\d{8}$/,
password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/,
url: /^https?:\/\/.+/i,
number: /^-?\d+(\.\d+)?$/,
integer: /^-?\d+$/,
chinese: /^[\u4e00-\u9fa5]+$/
},
validate: function(value, rule) {
var pattern = this.patterns[rule];
if (!pattern) return { valid: true };
return { valid: pattern.test(value) };
},
validateAll: function(data, rules) {
var errors = {};
for (var field in rules) {
var result = this.validate(data[field], rules[field]);
if (!result.valid) errors[field] = rules[field] + " 格式錯誤";
}
return { isValid: Object.keys(errors).length === 0, errors: errors };
}
};
// 使用
var result = Validator.validateAll({
email: "test@example.com",
phone: "0912345678",
password: "Abc12345"
}, {
email: "email",
phone: "phone",
password: "password"
});
console.log(result); // { isValid: true, errors: {} }
總結
JavaScript 正則表達式雖不如 C#/Java 功能豐富 (缺乏命名捕獲組、反向引用、條件匹配等進階功能),但涵蓋 90% 以上前端驗證需求。掌握 test (布林判斷)、exec (詳細匹配)、match (字串視角)、replace (替換)、split (分割) 五大核心方法,配合常用模式庫,足以應付絕大多數表單驗證、字串解析、資料清洗場景。