<分区>
为什么以下从true
变为false
;
var r = /e/gi;
r.test('e'); // true
r.test('e'); // false
然后继续切换true
, false
, true
, false
......
标签 javascript regex
<分区>
为什么以下从true
变为false
;
var r = /e/gi;
r.test('e'); // true
r.test('e'); // false
然后继续切换true
, false
, true
, false
......
最佳答案
这是因为 g
标志。它开始记住匹配项的最后一个索引,当您下次执行 r.test
时,它会从该索引开始。这就是它在 true
和 false
之间交替的原因。试试这个
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:
- If
lastIndex
is greater than the length of the string,test()
andexec()
fail, thenlastIndex
is set to 0.- 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 atlastIndex
.- 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, andlastIndex
is reset to 0.- 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/