gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:39:46 26 4
gpt4 key购买 nike

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

Performsa regular expression match of stringagainst the regular expression andreturns an Array object containing theresults of the match, or null if thestring did not match The stringToString(string) is searched for anoccurrence of the regular expressionpattern 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 resultand 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 samevalue as 15.10.2.1'sNCapturingParens.)
  14. Return a new array with the following properties:
  • The indexproperty is set to the position of thematched substring within the completestring S.
  • The input property is setto S.
  • The length property is set ton + 1.
  • The 0 property is set to thematched substring (i.e. the portion ofS between offset i inclusive andoffset e exclusive).
  • For eachinteger i such that i > 0 and i ≤ n,set the property named ToString(i) tothe ith element of r's captures array.

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com