量词
量词表示要匹配的字符或表达式的数量。
尝试一下
类型
字符集 | 意义 |
---|---|
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”为非负整数,并且 |
|
默认情况下,像
|
示例
重复模式
const wordEndingWithAs = /\w+a+\b/;
const delicateMessage = "This is Spartaaaaaaa";
console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]
统计单词
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"]
可选字符
const britishText = "He asked his neighbour a favour.";
const americanText = "He asked his neighbor a favor.";
const regexpEnding = /\w+ou?r/g;
// \w+ 一个及以上字母
// o 跟随字母“o”,
// u? 可能跟随字母“u”
// r 跟随字母“r”
console.table(britishText.match(regexpEnding));
// ["neighbour", "favour"]
console.table(americanText.match(regexpEnding));
// ["neighbor", "favor"]
贪婪匹配与非贪婪匹配
const text = "I must be getting somewhere near the center of the earth.";
const greedyRegexp = /[\w ]+/;
// [\w ] 一个拉丁字母或一个空格
// + 匹配一次及以上
console.log(text.match(greedyRegexp)[0]);
// "I must be getting somewhere near the center of the earth"
// 几乎所有文本都匹配(除了点字符)
const nonGreedyRegexp = /[\w ]+?/; // 注意问号
console.log(text.match(nonGreedyRegexp));
// "I"
// 尽可能少的匹配