gpt4 book ai didi

javascript 正则表达式与 g 标志匹配但不与 y 标志匹配

转载 作者:行者123 更新时间:2023-12-01 02:08:59 26 4
gpt4 key购买 nike

我无法理解为什么这会返回 true

let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = new RegExp(/\(/g);
reg.test(str);

let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = new RegExp(/\(/y);
reg.test(str);

返回 false。

将全局标志添加到粘性标志也没有帮助。

最佳答案

Adding the global flag to the sticky flag doesn't help either.

A regular expression defined as both sticky and global ignores the global flag.

The "y" flag indicates that it matches only from the index indicated by the lastIndex

您必须设置正则表达式的 lastIndex 属性,它默认为 0,并且该索引处没有任何 (,这就是为什么没有匹配的原因。 ( 出现在索引 5 处。

let str = '\\[\\]\\(\\)\\{\\}\\<\\>';

let reg = /\(/y; // No need for new RegExp

reg.lastIndex = str.indexOf('('); // 5
reg.test(str); // True

有关粘性标志的更多信息 here :

关于javascript 正则表达式与 g 标志匹配但不与 y 标志匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882928/

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