如何在JavaScript正则表达式中找到组的索引匹配?

Mic*_*sen 17 javascript regex

当我写一个正则表达式,如:

var m = /(s+).*?(l)[^l]*?(o+)/.exec("this is hello to you");
console.log(m);
Run Code Online (Sandbox Code Playgroud)

我得到一个包含以下内容的匹配对象:

{
  0: "s is hello",
  1: "s",
  2: "l",
  3: "o",
  index: 3,
  input: "this is hello to you"
}
Run Code Online (Sandbox Code Playgroud)

我知道整个比赛的索引来自该index属性,但我还需要知道匹配的组的开始和结束.使用简单的搜索将无法正常工作.在这个例子中,它将找到第一个'l'而不是在组中找到的那个.

有没有办法获得匹配组的偏移量?

bob*_*nce 16

您无法直接获取匹配组的索引.你要做的是先将每个角色放在一个匹配组中,即使是你不关心的角色:

var m= /(s+)(.*?)(l)([^l]*?)(o+)/.exec('this is hello to you');
Run Code Online (Sandbox Code Playgroud)

现在你已经完成了整个比赛:

['s is hello', 's', ' is hel', 'l', '', 'o']
Run Code Online (Sandbox Code Playgroud)

因此,您可以在组之前添加字符串的长度,以获得匹配索引到组索引的偏移量:

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
Run Code Online (Sandbox Code Playgroud)

  • “你无法直接获取比赛组的索引。”这在 2021 年仍然如此吗?感谢你的回答。 (3认同)
  • 它需要修改原始正则表达式 (2认同)
  • 有一个名为“d”的新标志将为您提供子匹配索引。 (2认同)

Del*_*lus 9

我写了一个简单的(初始化有点膨胀)javascript对象,以解决我最近一直在努力的项目上的这个问题.它的工作方式与接受的答案相同,但会生成新的正则表达式并自动提取您请求的数据.

var exp = new MultiRegExp(/(firstBit\w+)this text is ignored(optionalBit)?/i);
var value = exp.exec("firstbitWithMorethis text is ignored");

value = {0: {index: 0, text: 'firstbitWithMore'},
         1: null};
Run Code Online (Sandbox Code Playgroud)

Git Repo:我的MultiRegExp.希望这有助于那里的人.

编辑2015年8月:

试试我:MultiRegExp Live.