問題一、quantifier是什麼?
正規表達式的一種,種類如下:
*:匹配星號前的元素零次或多次。+:匹配星號前的元素一次或多次。?:匹配星號前的元素零次或一次。{n}:匹配符號前元素等於 n 次。{n,}:匹配符號前的元素至少 n 次,。{n,m}:匹配符號前元素至少 n 次,但不超過 m 次。const text = "aaaaabbbbcccc";
// *:匹配 a 0 次或多次 //quantifier* 是指min:0 max:infinity(無限大)
const pattern1 = /a*/;
console.log(text.match(pattern1)); // ["aaaaa"]
// +:匹配 b 1 次或多次 //quantifier+ 是指min:1 max:infinity(無限大)
const pattern2 = /b+/;
console.log(text.match(pattern2)); // ["bbbb"]
// ?:匹配 c 0 次或 1 次 //quantifier? 是指min:0 max:1
const pattern3 = /c?/;
console.log(text.match(pattern3)); // [""]
// {n}:匹配 a 恰好 3 次
const pattern4 = /a{3}/;
//quantifier{count} 大括號數字是幾,就匹配幾次
console.log(text.match(pattern4)); // ["aaa"]
// {n,}:匹配 b 至少 2 次 //quantifier{n,} min:2 max:infinity
const pattern5 = /b{2,}/;
console.log(text.match(pattern5)); // ["bbbb"]
// {n,m}:匹配 c 1 到 3 次 //quantifier{min, max} min:1 max:3
const pattern6 = /c{1,3}/;
console.log(text.match(pattern6)); // ["ccc"]
問題二、Disjunction是什麼?
| 是正規表達式的一種,先解析 | 左邊是否條件,若符合條件即結束回傳答案,若不符合條件,再比對 | 右邊是否符合條件。
請注意下面因為有Disjunction,所產生的匹配順序 :
/(?:(a)|(ab))(?:(c)|(bc))/.exec("abc");
// 結果 : ['abc', 'a', undefined, undefined, 'bc']
// Not ['abc', undefined, 'ab', 'c', undefined]
這個正規表達式 /^(?:(a)|(ab))(?:(c)|(bc))$/ 用來匹配。讓我們分解這個正規表達式:
^ 以 "a" 或 "ab" 開頭。(?: ... ) 是non-capturing group,用來將subpattern進行分組,但不會記得匹配結果,與capturing group相反。(a)|(ab) 表示第一個non-capturing group,它包含兩個subpattern:(a) 匹配單一字串 "a"。(ab) 匹配 "ab"。(?:(c)|(bc)) 表示第二個non-capturing group,它也包含兩個subpattern:(c) 匹配單一字串 "c"。(bc) 匹配"bc"。這個正規表達式如何運作:
"abc" 匹配整個正規表達式,因為它以 "a" 開頭,以 "c" 結尾。所以整個匹配結果是 "abc"。(a) 子模式匹配了 "a"。(ab) 子模式未匹配。(c) 子模式未匹配。(bc) 子模式匹配了 "bc"。正規表達式的 exec 方法返回一個陣列,包含整個匹配 "abc",以及每個non-capturing group中的匹配結果。未匹配的部分用 undefined 表示。
所以 ['abc', 'a', undefined, undefined, 'bc'] 是 exec 方法的返回結果,其中 'abc' 是整個匹配,'a' 是第一個subpattern (a) 的匹配結果,undefined 表示未匹配的部分。
問題三、?: 是什麼?
?: 是正規表達式的一種,是non-capturing group,他的功能有點像( )grouping operator。如果不需要去記憶匹配後的文字,又需要提升效能,也不會因為內部包含有意義的capturing groups,而產生混淆。
( )是grouping operator,範例如下面程式碼 :
console.log(1 + 2 * 3); // 1 + 6
// Expected output: 7
console.log(1 + 2 * 3); // 1 + 6
// Expected output: 7
console.log((1 + 2) * 3); // 3 * 3
// Expected output: 9
console.log(1 * 3 + 2 * 3); // 3 + 6
// Expected output: 9
(?:pattern)
?: 使用方法:
const text = "Hello, World!";
const regex = /(?:Hello), (?:World)!/;
const result = text.match(regex);
if (result) {
console.log(result[0]); // 輸出: "Hello, World!"
} else {
console.log("沒匹配到");
}
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping