循环匹配
一个常见的事情是,找出字符串中所有模式的出现位置,这种情况下,我们可以在循环中使用lastIndex和exec访问匹配的对象。
let input = "A string with 3 numbers in it... 42 and 88.";let number = /\b(\d+)\b/g;let match;while (match = number.exec(input)) {console.log("Found", match[0], "at", match.index);}// → Found 3 at 14// Found 42 at 33// Found 88 at 40
这里我们利用了赋值表达式的一个特性,该表达式的值就是被赋予的值。因此通过使用match=re.exec(input)作为while语句的条件,我们可以在每次迭代开始时执行匹配,将结果保存在变量中,当无法找到更多匹配的字符串时停止循环。
