循环匹配

一个常见的事情是,找出字符串中所有模式的出现位置,这种情况下,我们可以在循环中使用lastIndexexec访问匹配的对象。

  1. let input = "A string with 3 numbers in it... 42 and 88.";
  2. let number = /\b(\d+)\b/g;
  3. let match;
  4. while (match = number.exec(input)) {
  5. console.log("Found", match[0], "at", match.index);
  6. }
  7. // → Found 3 at 14
  8. // Found 42 at 33
  9. // Found 88 at 40

这里我们利用了赋值表达式的一个特性,该表达式的值就是被赋予的值。因此通过使用match=re.exec(input)作为while语句的条件,我们可以在每次迭代开始时执行匹配,将结果保存在变量中,当无法找到更多匹配的字符串时停止循环。