javascript - 为什么带有全局标志的正则表达式会给出错误的结果?

标签 javascript regex

当我使用全局标志和不区分大小写标志时,此正则表达式有什么问题?查询是用户生成的输入。结果应该是[true, true]。

var query = 'Foo B';
var re = new RegExp(query, 'gi');
var result = [];
result.push(re.test('Foo Bar'));
result.push(re.test('Foo Bar'));
// result will be [true, false]
<小时/>

var reg = /^a$/g;
for(i = 0; i++ < 10;)
   console.log(reg.test("a"));

最佳答案

带有 g 标志的 RegExp 对象会跟踪 lastIndex发生匹配的位置,因此在后续匹配中,它将从上次使用的索引开始,而不是从 0 开始。看一下:

var query = 'Foo B';
var re = new RegExp(query, 'gi');
console.log(re.lastIndex);

console.log(re.test('Foo Bar'));
console.log(re.lastIndex);

console.log(re.test('Foo Bar'));
console.log(re.lastIndex);

如果您不想在每次测试后手动将 lastIndex 重置为 0,只需删除 g 标志即可。

这是规范规定的算法(第 15.10.6.2 节):

RegExp.prototype.exec(string)

Performs a regular expression match of string against the regular expression and returns an Array object containing the results of the match, or null if the string did not match The string ToString(string) is searched for an occurrence of the regular expression pattern as follows:

  1. Let R be this RexExp object.
  2. Let S be the value of ToString(string).
  3. Let length be the length of S.
  4. Let lastIndex be the value of the lastIndex property on R.
  5. Let i be the value of ToInteger(lastIndex).
  6. If the global property is false, let i = 0.
  7. If i < 0 or i > length then set the lastIndex property of R to 0 and return null.
  8. Call [[Match]], giving it the arguments S and i. If [[Match]] returned failure, go to step 9; otherwise let r be its State result and go to step 10.
  9. Let i = i+1.
  10. Go to step 7.
  11. Let e be r's endIndex value.
  12. If the global property is true, set the lastIndex property of R to e.
  13. Let n be the length of r's captures array. (This is the same value as 15.10.2.1's NCapturingParens.)
  14. Return a new array with the following properties:
  • The index property is set to the position of the matched substring within the complete string S.
  • The input property is set to S.
  • The length property is set to n + 1.
  • The 0 property is set to the matched substring (i.e. the portion of S between offset i inclusive and offset e exclusive).
  • For each integer i such that i > 0 and i ≤ n, set the property named ToString(i) to the ith element of r's captures array.

关于javascript - 为什么带有全局标志的正则表达式会给出错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658171/

相关文章:

javascript - 从 Html 中提取特定值

php - 如何在没有意外匹配的情况下在 PHP 的字符串中找到整个单词?

javascript - 将数字分成 3 位数字,其余的分为 2 位数字

python - 如何在 python 中将文本文件分段?

java - Google V8 的工作方式与 Java 虚拟机类似吗?

javascript - 点击Chrome扩展程序中的页面

JavaScript/CSS/图像引用路径

javascript - 拉斐尔秩序对象

java - 为什么 Java 中的正则表达式无法将 s 识别为空格字符?

javascript - 如何使用纯 JavaScript 获取 div 内图像集的 src 值?