是否有任何Javascript函数从指定的索引中进行正则表达式匹配

Is there any Javascript function which does regex match from specified index

本文关键字:索引 正则表达式 任何 Javascript 函数 是否      更新时间:2023-09-26

是否有如下功能:

var regex=/'s*('w+)/;
var s="abc def ";
var m1=regex.exec(s,0); // -> matches "abc"
var m2=regex.exec(s,3); // -> matches "def"

我知道替代方案是:

var regex=/'s*('w+)/;
var s="abc def ";
var m1=regex.exec(s); // -> matches "abc"
var m2=regex.exec(s.substring(3)); // -> matches " def"

但我担心的是,如果s很长,并且s.substring被调用了很多次,那么一些实现可能会在多次复制长字符串的情况下效率很低。

是的,如果正则表达式具有g全局修饰符,则可以使exec从特定索引开始。

var regex=/'s*('w+)/g; // give it the "g" modifier
regex.lastIndex = 3;   // set the .lastIndex property to the starting index
var s="abc def ";
var m2=regex.exec(s); // -> matches "def"

如果您的第一个代码示例有g修饰符,那么它将按照您编写的方式工作,原因与上面的相同。使用g,它会自动将.lastIndex设置为上一次匹配结束后的索引,因此下一次调用将从那里开始。

所以这取决于你需要什么。

如果您不知道会有多少匹配,常见的方法是在循环中运行exec

var match,
    regex = /'s*('w+)/g,
    s = "abc def ";
while(match = regex.exec(s)) {
    alert(match);
}

或者作为do-while

var match,
    regex = /'s*('w+)/g,
    s = "abc def ";
do {
    match = regex.exec(s);
    if (match)
        alert(match);
} while(match);

我认为没有任何正则表达式方法可以做到这一点。如果你担心性能,我只会存储完整的字符串和剪切的字符串,这样substring只调用一次:

var regex=/'s*('w+)/;
var s="abc def ";
var shorts = s.substring(3);
var m1=regex.exec(s); // -> matches "abc"
var m2=regex.exec(shorts); // -> matches " def"