为什么RegEx.test会在后续调用中更改结果? [英] Why does RegEx.test changes the result in subsequent calls?

查看:79
本文介绍了为什么RegEx.test会在后续调用中更改结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下内容从 true 转到 false ;

Why does the following go from true to false;

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

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

and then it continue switching true, false, true, false ......

推荐答案

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

Its because of the g flag. It starts remembering the last index of the match and when you do r.test next time, it starts from that index. That is why it alternates between true and false. Try this

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


lastIndex 是正则表达式的读/写整数属性指定开始下一场比赛的索引
...

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

仅当正则表达式使用g标志指示全局搜索时才设置此属性。以下规则适用:

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


  1. 如果 lastIndex 大于字符串的长度, test() exec()失败,然后 lastIndex 设置为0.

  2. 如果 lastIndex 等于字符串的长度,并且正则表达式与空字符串匹配,然后正则表达式匹配从 lastIndex 开始的输入。

  3. 如果 lastIndex 等于字符串的长度,如果正则表达式与空字符串不匹配,则正则表达式输入不匹配, lastIndex 重置为0。 / strong>

  4. 否则, lastIndex 将设置为最近一次匹配后的下一个位置。

  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.

The bold text above answers the behaviour you observed. After the first match, e, the lastIndex is set to 1, to indicate the index from which the next match should be tried. According to the 3rd point seen above, since the lastIndex is equal to the length of the string and the regular expression doesn't match the empty string, it returns false and resets lastIndex to 0.

这篇关于为什么RegEx.test会在后续调用中更改结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆