尽可能多的匹配字符。
又称非贪婪模式,尽可能少的匹配字符。
量词默认是贪婪的,尽可能多的匹配字符。
如果让量词变成惰性(不贪婪)的,在量词后面添加上 ?。
const regex = /[a-zA-Z]{2,4}/g;
const string = "ab abc abcd abcde";
console.log(string.match(regex));
// ["ab", "abc", "abcd", "abcd"]
const regex = /[a-zA-Z]{2,4}?/g;
const string = "ab abc abcd abcde";
console.log(string.match(regex));
// ["ab", "ab", "ab", "cd", "ab", "cd"]
const regex = /[a-zA-Z]{2}?/g;
const string = "ab abc abcd abcde";
console.log(string.match(regex));
// ["ab", "ab", "ab", "cd", "ab", "cd"]
const regex = /[a-zA-Z]*?/g;
const string = "ab abc abcd abcde";
console.log(string.match(regex));
// ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""] 长度 18
匹配0次,"ab abc abcd abcde"中能匹配的位置有18个。
const regex = /[a-zA-Z]??/g;
const string = "ab abc abcd abcde";
console.log(string.match(regex));
// ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""] 长度 18
和4例子一样。
const regex = /[a-zA-Z]+?/g;
const string = "ab abc abcd abcde";
console.log(string.match(regex));
// ["a", "b", "a", "b", "c", "a", "b", "c", "d", "a", "b", "c", "d", "e"] 长度 14