在Javascript中返回正则表达式匹配()的位置?

sta*_*gas 128 javascript regex match string-matching

有没有办法在Javascript中检索正则表达式匹配()的结果字符串中的(起始)字符位置?

Gum*_*mbo 191

exec返回具有index属性的对象:

var match = /bar/.exec("foobar");
if (match) {
    console.log("match found at " + match.index);
}
Run Code Online (Sandbox Code Playgroud)

对于多场比赛:

var re = /bar/g,
    str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
    console.log("match found at " + match.index);
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:使用`re`作为变量,添加`g`修饰符都是至关重要的!否则你将获得无限循环. (9认同)
  • 谢谢你的帮助!您还能告诉我如何找到多个匹配项的索引吗? (3认同)

sta*_*gas 57

这是我想出的:

// Finds starting and ending positions of quoted text
// in double or single quotes with escape char support like \" \'
var str = "this is a \"quoted\" string as you can 'read'";

var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;

while (match = patt.exec(str)) {
  console.log(match.index + ' ' + patt.lastIndex);
}
Run Code Online (Sandbox Code Playgroud)

  • `match.index + match [0] .length`也适用于最终位置. (13认同)
  • @David,我的意思是独占结束位置,例如通过“.slice()”和“.substring()”获取的。正如你所说,包容性结束将减少 1。(请注意,包含通常意味着匹配内最后一个字符的索引,除非它是一个空匹配,其中它是 1 *before* 匹配,并且可能在字符串外部完全为空匹配的“-1”...) (2认同)

bri*_*uth 17

在现代浏览器中,您可以使用string.matchAll()完成此操作

这种方法 vs 的好处RegExp.exec()是它不依赖于有状态的正则表达式,如@Gumbo's answer

let regexp = /bar/g;
let str = 'foobarfoobar';

let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
    console.log("match found at " + match.index);
});
Run Code Online (Sandbox Code Playgroud)


Jim*_*nny 13

来自关于String 方法的developer.mozilla.org文档.match():

返回的Array有一个额外的input属性,它包含已解析的原始字符串.此外,它还有一个index属性,表示字符串中匹配的从零开始的索引.

处理非全局正则表达式(即正则表达式中没有g标志)时,返回的值.match()有一个index属性......您所要做的就是访问它.

var index = str.match(/regex/).index;
Run Code Online (Sandbox Code Playgroud)

以下示例显示了它的工作原理:

var str = 'my string here';

var index = str.match(/here/).index;

alert(index); // <- 10
Run Code Online (Sandbox Code Playgroud)

我已成功测试了这一回到IE5.

  • 请注意,如果您使用全局标志执行 str.match(/here/g),则 match.index 将是未定义的。 (2认同)

Jim*_*dra 6

您可以使用searchString对象的方法.这仅适用于第一场比赛,否则将按照您的描述进行.例如:

"How are you?".search(/are/);
// 4
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我最近发现的一个很酷的功能,我在控制台上尝试了一下,它似乎可以正常工作:

var text = "border-bottom-left-radius";

var newText = text.replace(/-/g,function(match, index){
    return " " + index + " ";
});
Run Code Online (Sandbox Code Playgroud)

其中返回:“边界6底13左18半径”

所以这似乎是您想要的。

  • 请注意,替换功能也会添加捕获组,因此请注意,位置总是替换功能“ arguments”中的“倒数第二个”条目。不是“第二个论点”。函数参数是“完全匹配,group1,group2,....,匹配索引,与之匹配的完整字符串” (6认同)