首页 > 解决方案 > 如何使用RegExp计算使用js的字符串中由相同字符组成的substr

问题描述

js中有什么方法可以使用RegExp并str.match()计算字符串中子字符串的组合吗?我正在努力实现以下目标:

给定一个字符串:

'999999000'

我需要找到99字符串中存在的所有组合,上述字符串的预期结果是 5,因为您可以组合以下对中的索引来创建99

index 0 and 1
index 1 and 2
index 2 and 3
index 3 and 4
index 4 and 5

现在我尝试通过以下方式使用 match 方法:

    let re = new RegExp("99","gi");
    let matches = "999999000".match(re).length;
    console.log(matches);

但它抛出的结果是3。

请注意,上面的代码片段适用于以下情况:

    let re = new RegExp("99","gi");
    let matches = "00990099099099".match(re).length;
    console.log(matches);

我知道这个问题可以通过迭代字符串来找到所有'99'组合来解决,但我想使用正则表达式和str.match

标签: javascriptregexstring

解决方案


您可以使用积极的前瞻来断言 2 次 9:

(?=(9{2}))

const strings = [
  "999999000",
  "00990099099099"
];
let re = new RegExp("(?=(9{2}))", "gi");
strings.forEach((s) => {
  console.log(s + " ==> " + s.match(re).length);
});


推荐阅读