正則表達式(RegExp)
什麼是正則表達式?
比喻:正則就像一個模式匹配器 🔣
你給它一個「模式」(pattern),它幫你從文字中找出所有符合的部分。
建立正則
// 方式 1:字面值(常用)
let pattern = /hello/; // ← 匹配 "hello"
// 方式 2:建構函式(動態建立時用)
let pattern2 = new RegExp("hello");
// 加旗標
let pattern3 = /hello/gi; // g=全域, i=不分大小寫
常用方法
let regex = /小[明華美]/g;
// test — 測試是否匹配
regex.test("小明你好"); // ← true
// match — 找出所有匹配
"小明和小華".match(/小[明華美]/g); // ← ["小明", "小華"]
// replace — 取代
"小明好棒".replace(/小明/, "小華"); // ← "小華好棒"
// search — 找位置
"Hello World".search(/World/); // ← 6
// split — 分割
"a,b;c|d".split(/[,;|]/); // ← ["a", "b", "c", "d"]
常用模式
// 字元類
/[abc]/ // a 或 b 或 c
/[a-z]/ // a 到 z
/[0-9]/ // 0 到 9
/[^abc]/ // 不是 a, b, c
// 特殊字元
/\d/ // 數字(等同 [0-9])
/\D/ // 非數字
/\w/ // 字母數字底線(等同 [a-zA-Z0-9_])
/\W/ // 非字母數字
/\s/ // 空白字元
/\S/ // 非空白字元
/./ // 任意字元(換行除外)
// 量詞
/a*/ // a 出現 0 次或多次
/a+/ // a 出現 1 次或多次
/a?/ // a 出現 0 次或 1 次
/a{3}/ // a 剛好 3 次
/a{2,5}/ // a 2~5 次
/a{3,}/ // a 至少 3 次
// 錨點
/^hello/ // 開頭是 hello
/world$/ // 結尾是 world
/\bhello\b/ // 完整單詞 hello
實用驗證範例
// Email 驗證(簡易版)
function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
// 手機號碼(台灣)
function isValidPhone(phone) {
return /^09\d{8}$/.test(phone);
}
// 密碼強度(至少 8 字元,包含大小寫和數字)
function isStrongPassword(pwd) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(pwd);
}
// 取代敏感字
function censorBadWords(text) {
return text.replace(/壞詞|髒話/g, "***");
}
// 提取數字
"價格是 NT$1,200 元".match(/\d+/g); // ["1", "200"]
"價格是 NT$1,200 元".match(/[\d,]+/g); // ["1,200"]
分組與捕獲
// 捕獲組 ()
let match = "2024-01-15".match(/(\d{4})-(\d{2})-(\d{2})/);
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 組)
// 命名捕獲組
let match2 = "2024-01-15".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(match2.groups.year); // "2024"
console.log(match2.groups.month); // "01"
// 在 replace 中使用捕獲組
"2024-01-15".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
// → "15/01/2024"