正規表達式
正規表達式的使用方式
regex.方法(字串)
.test()
是否有匹配到 return true or false
let regex = /abc/;
console.log(regex.test('abcdef')); // 輸出:true
console.log(regex.test('xyz')); // 輸出:false
.exec()
const regex = /([a-z]+)@([a-z]+)\.com/;
const exec = regex.exec('abc@def.com');
const exec2 = regex.exec('not-an-email');
console.log(exec);
//輸出:['abc@def.com', 'abc', 'def', index: 0, input: 'abc@def.com', groups: undefined]
console.log(exec[2]); // "def"
console.log(exec2)
字串.方法(regex)
.split()
.match()
const str = "I have 5 apples and 3 oranges.";
const regex = /\d+/g;
const matches = str.match(regex);
console.log(matches); // 輸出:['5', '3']
.replace()
const str = "I have 5 apples and 3 oranges.";
const regex = /\d+/g;
const nstr = str.replace(regex, 'X');
console.log(nstr); // I have X apples and X oranges.
.search()
斷言
前瞻斷言(Lookahead Assertion)
- 正向前瞻(Positive Lookahead Assertion):語法為
(?=...)
它表示當前位置的後面(右邊)必須是括號內的字符 - 負向前瞻(Negative Lookahead Assertion):語法為
(?!...)
它表示當前的位置後面(右邊)不能是括號內的字符
後顧斷言(Lookbehind Assertion)
Warning
JavaScript 在 ES2018 版本之前不支援後顧,且後顧的長度是固定的不可使用* +
-
正向後顧(Positive Lookbehind Assertion):語法為
(?<=...)
它表示當前的位置前面(左邊)必須是括號內的字符 -
負向後顧(Negative Lookbehind Assertion):語法為
(?<!...)
它表示當前的位置前面(左邊)不能是括號內的字符。
嵌套
const text = "Alice: 95, Bob: 88, Charlie: 92, David: 85";
const regex = /\b\w+(?=: (?![9][0-9]\b))/g;
const matches = text.match(regex);
console.log(matches); // Output: ["Bob", "David"]
| 斷言類型 | 語法 | 描述 | 範例 | 範例說明 |
|---|---|---|---|---|
| 正向前瞻 | (?=...) |
當前位置後面必須是括號內的字符 |
/可愛(?=貓)/g |
匹配 '可愛貓' 的 '可愛' 不匹配 '可愛狗' 的 '可愛' |
| 負向前瞻 | (?!...) |
當前位置後面不能是括號內的字符 |
/可愛(?!貓)/g |
匹配 '可愛狗' 的 '可愛' 不匹配 '可愛貓' 的 '可愛' |
| 正向後顧 | (?<=...) |
當前位置前面必須是括號內的字符 |
/(?<=可愛)貓/g |
匹配 '可愛貓' 的 '貓' 不匹配 '野生貓' 的 '貓' |
| 負向後顧 | (?<!...) |
當前位置前面不能是括號內的字符 |
/(?<!可愛)貓/g |
匹配 '野生貓' 的 '貓' 不匹配 '可愛貓' 的 '貓' |
分組
捕獲分組
const reg = /([a-z]+)@([a-z]+)\.com/;
const str = "abc@def.com";
const matches = str.match(reg);
console.log( matches[0]); // "abc@def.com"
console.log( matches[1]); // "abc"
console.log( matches[2]); // "def"
非捕獲分組
const reg = /(?:[a-z]+)@(?:[a-z]+)\.com/;
const str = "abc@def.com";
const matches = str.match(reg);
console.log( matches[0]); // "abc@def.com"
console.log( matches[1]); // undefined
console.log( matches[2]); // undefined
貪婪與非貪婪
貪婪匹配
var str = 'abcabcabc';
var reg = /a.*c/;
var result = str.match(reg);
console.log(result); // 輸出:['abcabcabc']
非貪婪匹配
var str = 'abcabcabc';
var reg = /a.*?c/;
var result = str.match(reg);
console.log(result); // 輸出:['abc']
參考資料:
Regex101
Regexone
RegexUnicode