获取字符串中所有与正则表达式匹配的子字符串

5

可能是重复问题:
如何在JavaScript中与PHP的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" 的起始和结束索引。

2个回答

12

使用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`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接