如何获取 JavaScript 正则表达式子匹配的位置

How to get the position of a JavaScript regexp sub-match?

本文关键字:位置 正则表达式 JavaScript 何获取 获取      更新时间:2023-09-26

这是我的正则表达式的简化版本:

re = /a(.*)b(.*)c(.*)d/;
match = re.exec("axbxcxd");

正如预期的那样,这导致match[1]match[2]match[3]"x",但我需要得到中间匹配 2 的位置。在 Python 中,我可以使用 match.position(2) 。JavaScript 中是否有任何等效的方法来获取子匹配的位置? 我不能只搜索匹配的字符串,因为其他一些子匹配项可能是相同的。

JavaScript 还没有

一个集成的 API 来返回子匹配项的位置。

ECMAScript 邮件列表中有一些关于添加这样一个 API 的讨论,尽管到目前为止还没有结果。

已经有一些工具,如regexplained和HiFi Regex Tester。尽管它们无法确定子匹配项的位置,例如/aa(a)/匹配字符串"aaa"

这些工具的作用是搜索regexp.exec()返回的主匹配项中的子匹配项 string.indexOf() .下面是一些示例代码:

var string = "xxxabcxxx";
var regexp = /a(b(c))/g;
var matches = regexp.exec(string);
if (matches) {
  matches[0] = {
    text: matches[0],
    pos: regexp.lastIndex - matches[0].length
  };
  for(var i = 1; i < matches.length; i++) {
    matches[i] = {
      text: matches[i],
      pos: string.indexOf(matches[i], matches[0].pos)
    };
  }
}
console.log(matches);

这将输出一个包含子匹配位置的匹配对象数组:

  [
    {
      text: "abc",
      pos: 3
    },
    {
      text: "bc",
      pos: 3
    },
    {
      text: "c",
      pos: 5
    }
  ]

但再次注意,上面的代码与上述工具一样,并非适用于所有情况。

match对象有一个名为 index 的东西,我认为这就是你要找的:

["axbxcxd", "x", "x", "x", index: 0, input: "axbxcxd"]


编辑

还行。我想我第一次没有正确回答这个问题。以下是更新的答案:

re = /a(.*)b(.*)c(.*)d/;
str = "axbxcxd";
match = re.exec(str);
searchStr = match[1]; //can be either match[2],match[3]
searchStrLen = match[1].length; //can be either match[2],match[3]
var index, indices = []
var startIndex = 0;
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + searchStrLen;
}
console.log(indices[1]); // index of match[2]
console.log(indices[0]); // index of match[1]
console.log(indices[2]); // index of match[3] .. and so on, because some people don't get it with a single example

这可能是一个黑客,但应该有效。工作小提琴:http://jsfiddle.net/8dkLq8m0/