javascript - 为什么 RegEx.test 会在后续调用中更改结果?

标签 javascript regex

<分区>

为什么以下从true变为false

var r = /e/gi;
r.test('e'); // true
r.test('e'); // false

然后继续切换true, false, true, false ......

最佳答案

这是因为 g 标志。它开始记住匹配项的最后一个索引,当您下次执行 r.test 时,它会从该索引开始。这就是它在 truefalse 之间交替的原因。试试这个

var r = /e/gi;
console.log(r.test('e'));
# true
console.log(r.lastIndex);
# 1
console.log(r.test('e'));
# false
console.log(r.lastIndex);
# 0
console.log(r.test('e'));
# true
console.log(r.lastIndex);
# 1
console.log(r.test('e'));
# false

RegExp.lastIndex 上引用 MDN 文档,

The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match. ...

This property is set only if the regular expression used the "g" flag to indicate a global search. The following rules apply:

  1. If lastIndex is greater than the length of the string, test() and exec() fail, then lastIndex is set to 0.
  2. If lastIndex is equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting at lastIndex.
  3. If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
  4. Otherwise, lastIndex is set to the next position following the most recent match.

上面的粗体文本回答了您观察到的行为。在第一个匹配项 e 之后,lastIndex 被设置为 1,以指示应从中尝试下一个匹配项的索引。根据上面看到的第3点,由于lastIndex等于字符串的长度并且正则表达式不匹配空字符串,它返回false并重置lastIndex 为 0。

关于javascript - 为什么 RegEx.test 会在后续调用中更改结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28910934/

相关文章:

javascript - babel,带有nodemon脚本的webpack?

javascript - knockoutjs 映射插件从对象中删除功能

regex - 正则表达式 : How to put single quotes around XML attribute values?

javascript - 样式表更新和模式添加到每个下拉项后,下拉菜单停止工作

javascript - 访问 jade 循环内的 Controller 变量

JavaScript 构造函数和原型(prototype)对象

Java正则表达式

regex - 什么是?意思是?

c# - 使用正则表达式删除文本 block ,仅匹配第一次出现

c# - 正则表达式:找到整数但不是 float