我无法理解为什么这会返回 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/