当我写一个正则表达式时:
var m = /(s+).*?(l)[^l]*?(o+)/.exec("this is hello to you");
console.log(m);
我得到一个包含以下内容的匹配对象:
{
0: "s is hello",
1: "s",
2: "l",
3: "o",
index: 3,
input: "this is hello to you"
}
我从 index
属性中知道整个匹配的索引,但我还需要知道匹配组的开始和结束。使用简单的搜索是行不通的。在此示例中,它将查找第一个“l”而不是在组中找到的那个。
有没有办法得到匹配组的偏移量?
您不能直接获取匹配组的索引。您要做的是首先将每个 Angular 色放入匹配组中,即使是您不关心的 Angular 色也是如此:
var m= /(s+)(.*?)(l)([^l]*?)(o+)/.exec('this is hello to you');
现在你已经得到了部分的整场比赛:
['s is hello', 's', ' is hel', 'l', '', 'o']
因此,您可以将组之前的字符串的长度相加,以获得从匹配索引到组索引的偏移量:
function indexOfGroup(match, n) {
var ix= match.index;
for (var i= 1; i<n; i++)
ix+= match[i].length;
return ix;
}
console.log(indexOfGroup(m, 3)); // 11