gpt4 book ai didi

javascript - JavaScript 正则表达式中 'y' 粘性模式修饰符的用途是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 05:57:37 26 4
gpt4 key购买 nike

MDN 为 JavaScript RegExp 引入了“y”粘性标志。这是一个documentation excerpt :

y

sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).

还有一个例子:

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'

但在这种情况下,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'

相同的输出。所以我想可能还有其他关于 'y' 标志的东西,而且 MDN 的示例似乎不是这个修饰符的真正用例,因为它似乎只是在这里作为 'g' 全局修饰符的替代品。

那么,这个实验性“y”粘性标志的真实用例可能是什么? “仅从 RegExp.lastIndex 属性匹配”的目的是什么?当与 RegExp.prototype.exec 一起使用时,它与“g”的区别是什么?

感谢关注。

最佳答案

yg 之间的区别Practical Modern JavaScript 中有描述。 :

The sticky flag advances lastIndex like g but only if a match is found starting at lastIndex, there is no forward search. The sticky flag was added to improve the performance of writing lexical analyzers using JavaScript...

至于一个真实的用例,

It could be used to require a regular expression match starting at position n where n is what lastIndex is set to. In the case of a non-multiline regular expression, a lastIndex value of 0 with the sticky flag would be in effect the same as starting the regular expression with ^ which requires the match to start at the beginning of the text searched.

这是该博客中的一个示例,其中 lastIndex 属性在 test 方法调用之前被操作,从而强制产生不同的匹配结果:

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));
});

结果:

"found a match at" 0 ":" false
"found a match at" 1 ":" true
"found a match at" 2 ":" false

关于javascript - JavaScript 正则表达式中 'y' 粘性模式修饰符的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30291436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com