量詞
量詞指示要匹配的字元或表示式的數量。
試一試
const ghostSpeak = "booh boooooooh";
const regexpSpooky = /bo{3,}h/;
console.log(ghostSpeak.match(regexpSpooky));
// Expected output: Array ["boooooooh"]
const modifiedQuote = "[He] ha[s] to go read this novel [Alice in Wonderland].";
const regexpModifications = /\[.*?\]/g;
console.log(modifiedQuote.match(regexpModifications));
// Expected output: Array ["[He]", "[s]", "[Alice in Wonderland]"]
const regexpTooGreedy = /\[.*\]/g;
console.log(modifiedQuote.match(regexpTooGreedy));
// Expected output: Array ["[He] ha[s] to go read this novel [Alice in Wonderland]"]
型別
| 字元 | 含義 |
|---|---|
x*
|
匹配前面項“x”0 次或更多次。例如, |
x+
|
匹配前面項“x”1 次或更多次。等同於 |
x?
|
匹配前面項“x”0 次或 1 次。例如, 如果緊接在量詞 |
x{n}
|
其中“n”是非負整數,精確匹配前面項“x”的“n”個出現。例如, |
x{n,}
|
其中“n”是非負整數,匹配前面項“x”的至少“n”個出現。例如, |
x{n,m}
|
其中“n”和“m”是非負整數且 |
|
|
預設情況下,像
|
示例
重複模式
在這個例子中,我們用 \w+ 匹配一個或多個單詞字元,然後用 a+ 匹配一個或多個字元“a”,最後用 \b 結束於一個單詞邊界。
const wordEndingWithAs = /\w+a+\b/;
const delicateMessage = "This is Spartaaaaaaa";
console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]
計數字符
在這個例子中,我們匹配只有一個字母的單詞、有 2 到 6 個字母的單詞以及有 13 個或更多字母的單詞。
const singleLetterWord = /\b\w\b/g;
const notSoLongWord = /\b\w{2,6}\b/g;
const longWord = /\b\w{13,}\b/g;
const sentence = "Why do I have to learn multiplication table?";
console.table(sentence.match(singleLetterWord)); // ["I"]
console.table(sentence.match(notSoLongWord)); // [ "Why", "do", "have", "to", "learn", "table" ]
console.table(sentence.match(longWord)); // ["multiplication"]
可選字元
在這個例子中,我們匹配以“our”或“or”結尾的單詞。
const britishText = "He asked his neighbour a favour.";
const americanText = "He asked his neighbor a favor.";
const regexpEnding = /\w+ou?r/g;
// \w+ One or several letters
// o followed by an "o",
// u? optionally followed by a "u"
// r followed by an "r"
console.table(britishText.match(regexpEnding));
// ["neighbour", "favour"]
console.table(americanText.match(regexpEnding));
// ["neighbor", "favor"]
貪婪與非貪婪
在這個例子中,我們用 [\w ]+ 和 [\w ]+? 匹配一個或多個單詞字元或空格。第一個是貪婪的,第二個是非貪婪的。請注意第二個是如何在滿足最小要求後立即停止的。
const text = "I must be getting somewhere near the center of the earth.";
const greedyRegexp = /[\w ]+/;
console.log(text.match(greedyRegexp)[0]);
// "I must be getting somewhere near the center of the earth"
// almost all of the text matches (leaves out the dot character)
const nonGreedyRegexp = /[\w ]+?/; // Notice the question mark
console.log(text.match(nonGreedyRegexp));
// "I"
// The match is the smallest one possible