用法
const regex1 = RegExp('foo*', 'g');
const str1 = 'table football, foosball';
let array1;
while ((array1 = regex1.exec(str1)) !== null) {
console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
// expected output: "Found foo. Next starts at 9."
// expected output: "Found foo. Next starts at 19."
}
原理
RegExp对象是
有状态的。会将上次成功匹配后的位置记录在lastIndex中,利用这个特性。exec可用来对单个字符串中的多次匹配结果进行逐条遍历。