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

标签 javascript node.js regex

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

相关文章:

angularjs - 平均堆栈 : Cannot load localhost page after latest git pull "Get/- - ms - -"

r - strsplit 返回添加了反斜杠和引号的嵌套列表\"

javascript - 无法更改选择中的选定选项

javascript - nodejs看不到已安装的mysql模块

javascript - 查找 ID 数组,并将它们映射到单独模式中的项目数组

node.js - 如何在Docker容器中运行npm命令?

javascript - 如何在 vuejs 的自定义表格组件中使用插槽/作用域插槽?

javascript - 单击时抓取 href 标签

regex - 结合两个正则表达式

c# - 如何显示哪个子正则表达式匹配失败?