【问题标题】:How to match an overlapping pattern multiple times using RegExp如何使用 RegExp 多次匹配重叠模式
【发布时间】:2018-04-10 03:22:27
【问题描述】:

有没有一种使用正则表达式的方法,给定正则表达式 /aa/g(或类似的)它匹配字符串“aaa”的两倍?假设第一个匹配是前两个a,第二个匹配是最后两个a。

类似这样的:

  • 比赛 1:'aa'a
  • 比赛 2:a'aa'

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以将reglastIndex更改为index+1

    let str = "aaa",
      reg = /aa/g,
      next = reg.exec(str),
      res = [];
    while (next) {
      res.push(next[0]);
      reg.lastIndex = next.index + 1;
      next = reg.exec(str);
    }
    console.log(res);

    【讨论】:

      【解决方案2】:

      您可以捕获两个 a 的内部前瞻,然后返回并匹配一个 a 字符。

          let pattern = /(?=(a{2}))a/g;
          let resultMatches = [];
          let match;
          let stringToCheck = 'aaa';
      
          while ((match = pattern.exec(stringToCheck)) !== null)
              resultMatches.push(match[1]);
      
          console.log(resultMatches);

      使用'aaa'作为输入返回['aa','aa'],而使用'aaaa'作为输入返回['aa','aa','aa']

      【讨论】:

        猜你喜欢
        • 2012-07-14
        • 2019-09-23
        • 1970-01-01
        • 2012-02-18
        • 1970-01-01
        • 2011-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多