--- title: 量词 slug: Web/JavaScript/Guide/Regular_Expressions/Quantifiers translation_of: Web/JavaScript/Guide/Regular_Expressions/Quantifiers original_slug: Web/JavaScript/Guide/Regular_Expressions/量词 ---
{{jsSidebar("JavaScript Guide")}}
量词表示要匹配的字符或表达式的数量。
Characters | Meaning |
---|---|
x* |
将前面的项“x”匹配0次或更多次。例如,/bo*/匹配“A ghost booooed”中的“boooo”和“A bird warbled”中的“b”,但在“A goat grunt”中没有匹配。 |
x+ |
将前一项“x”匹配1次或更多次。等价于{1,}。例如,/a+/匹配“candy”中的“a”和“caaaaaaandy”中的“a”。 |
x? |
将前面的项“x”匹配0或1次。例如,/ e ?勒?/匹配angel中的el和angle中的le。 如果立即在任何量词*、+、?或{}之后使用,则使量词是非贪婪的(匹配最小次数),而不是默认的贪婪的(匹配最大次数)。 |
x{n} |
其中“n”是一个正整数,与前一项“x”的n次匹配。例如, |
x{n,} |
其中,“n”是一个正整数,与前一项“x”至少匹配“n”次。例如, |
x{n,m} |
其中,“n”是0或一个正整数,“m”是一个正整数,而m > n至少与前一项“x”匹配,最多与“m”匹配。例如,/a{1,3}/不匹配“cndy”中的“a”,“candy”中的“a”,“caandy”中的两个“a”,以及“caaaaaaandy”中的前三个“a”。注意,当匹配“caaaaaaandy”时,匹配的是“aaa”,即使原始字符串中有更多的“a”。 |
|
默认情况下,像
|
var wordEndingWithAs = /\w+a+/; var delicateMessage = "This is Spartaaaaaaa"; console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]
var singleLetterWord = /\b\w\b/g;
var notSoLongWord = /\b\w{1,6}\b/g;
var loooongWord = /\b\w{13,}\b/g;
var sentence = "Why do I have to learn multiplication table?";
console.table(sentence.match(singleLetterWord)); // ["I"]
console.table(sentence.match(notSoLongWord)); //
console.table(sentence.match(loooongWord)); // ["multiplication"]可选可选字符
var britishText = "He asked his neighbour a favour."; var americanText = "He asked his neighbor a favor."; var 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"]
var text = "I must be getting somewhere near the centre of the earth."; var greedyRegexp = /[\w ]+/; // [\w ] a letter of the latin alphabet or a whitespace // + one or several times console.log(text.match(greedyRegexp)[0]); // "I must be getting somewhere near the centre of the earth" // almost all of the text matches (leaves out the dot character) var nonGreedyRegexp = /[\w ]+?/; // Notice the question mark console.log(text.match(nonGreedyRegexp)); // "I" // The match is the smallest one possible
Specification |
---|
{{SpecName('ESDraft', '#sec-quantifier', 'RegExp: Quantifiers')}} |
For browser compatibility information, check out the main Regular Expressions compatibility table.