量词
量词指示要匹配的字符或表达式的数量。
试一试
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