【问题标题】:Get all substrings inside a string that match a regular expression [duplicate]获取与正则表达式匹配的字符串中的所有子字符串[重复]
【发布时间】:2012-08-15 10:19:41
【问题描述】:

可能重复:
How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

在 Javascript 中,是否可以在一个字符串中找到匹配正则表达式的所有子字符串的开始和结束索引?

函数签名:

function getMatches(theString, theRegex){
    //return the starting and ending indices of match of theRegex inside theString
    //a 2D array should be returned
}

例如:

getMatches("cats and rats", /(c|r)ats/);

应该返回数组[[0, 3], [9, 12]],表示字符串中“cats”和“rats”的开始和结束索引。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    使用match 查找与正则表达式匹配的所有子字符串。

    > "cats and rats".match(/(c|r)ats/g)
    > ["cats", "rats"]
    

    现在您可以使用indexOflength 来查找开始/结束索引。

    【讨论】:

      【解决方案2】:
      function getMatches(theString, theRegex){
          return theString.match(theRegex).map(function(el) {
              var index = theString.indexOf(el);
              return [index, index + el.length - 1];
          });
      }
      getMatches("cats and rats", /(c|r)ats/g); // need to use `g`
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 2012-07-03
        • 2011-11-08
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多