JavaScript RegExps中'y'粘滞模式修饰符的用途是什么?

ton*_*nix 5 javascript regex

MDN为JavaScript RegExp引入了'y'粘性标志.这是一个文档摘录:

ÿ

黏; 仅匹配目标字符串中此正则表达式的lastIndex属性指示的索引(并且不会尝试与任何后续索引匹配).

还有一个例子:

var text = 'First line\nSecond line';
var regex = /(\S+) line\n?/y;

var match = regex.exec(text);
console.log(match[1]);        // prints 'First'
console.log(regex.lastIndex); // prints '11'

var match2 = regex.exec(text);
console.log(match2[1]);       // prints 'Second'
console.log(regex.lastIndex); // prints '22'

var match3 = regex.exec(text);
console.log(match3 === null); // prints 'true'
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,g全局标志的使用实际上没有任何区别:

var text = 'First line\nSecond line';
var regex = /(\S+) line\n?/g;

var match = regex.exec(text);
console.log(match[1]);        // prints 'First'
console.log(regex.lastIndex); // prints '11'

var match2 = regex.exec(text);
console.log(match2[1]);       // prints 'Second'
console.log(regex.lastIndex); // prints '22'

var match3 = regex.exec(text);
console.log(match3 === null); // prints 'true'
Run Code Online (Sandbox Code Playgroud)

相同的输出.所以我猜可能还有关于'y'标志的其他内容,似乎MDN的例子不是这个修饰符的真实用例,因为它似乎只是作为'g'全局修饰符的替代.

那么,这个实验性的'y'粘性标志可能是一个真正的用例?它的目的是"仅从RegExp.lastIndex属性中匹配",以及与'g'在使用时的区别是什么RegExp.prototype.exec

感谢您的关注.

Wik*_*żew 7

差异之间yg在提供比约恩Tipling的博客.

粘性标志前进lastIndex,g只有从匹配开始lastIndex,才有正向搜索.添加了粘性标志以提高使用JavaScript 编写词法分析器的性能 ...

至于一个真实的用例,

它可用于需要一个正则表达式匹配起始位置n在那里n 是什么lastIndex设为.在非多线正则表达式的情况下,带有粘性标记的lastIndex0实际上与启动正则表达式相同,正则表达式^要求匹配在搜索的文本的开头处开始.

以下是该博客的示例,其中lastIndextest方法调用之前操作属性,从而强制执行不同的匹配结果:

var searchStrings, stickyRegexp;

stickyRegexp = /foo/y;

searchStrings = [
    "foo",
    " foo",
    "  foo",
];
searchStrings.forEach(function(text, index) {
    stickyRegexp.lastIndex = 1;
    console.log("found a match at", index, ":", stickyRegexp.test(text));
});
Run Code Online (Sandbox Code Playgroud)

结果:

"found a match at" 0 ":" false
"found a match at" 1 ":" true
"found a match at" 2 ":" false
Run Code Online (Sandbox Code Playgroud)