Regex.prototype.exec在搜索的第二次迭代时返回null [英] Regex.prototype.exec returns null on second iteration of the search

查看:155
本文介绍了Regex.prototype.exec在搜索的第二次迭代时返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个字符串中搜索几个匹配项。每个匹配最终链接到对象数组中的对象属性。找到匹配项后,该匹配项将替换为对象中的另一个属性。问题是代码将在第二次匹配时始终返回null。

I'd like to search a string for several matches. Each match is eventually linked to an object property in an object array. When a match is found, that match is replaced by another property within an object. The problem is the code will always return null on the second match.

这是测试我正在使用的案例。为了简化问题,我只用5号替换所有匹配,但请注意最终代码将用可变值替换匹配。

This is the test case that I am using. To simplify the problem, I just replace all matches with the number 5, but note that the final code will be replacing the match with a variable value.

下面是我用来测试和调试问题的代码。有趣的是,如果我更改 var str ='5 + QUESTION_2' QUESTION_2 已成功替换为5。从本质上讲,问题归结为第二个匹配总是返回null,即使它可以匹配。

Below is the code I'm using to test and debug the issue. The interesting thing is that if I change var str = '5 + QUESTION_2', QUESTION_2 is successfully replaced with 5. Essentially, the problem boils down to the second match always returning null even though it can be matched.

var re = /( |^)(QUESTION_1|QUESTION_2|QUESTION_3)( |$)/g;
var str = 'QUESTION_1 + QUESTION_2';
var rep = 5;

matches = re.exec(str);
var re2 = new RegExp("( |^)(" + matches[2] + ")( |$)", "g");
console.log(matches); // Returns a match on QUESTION_1
str = str.replace(re2, rep);
console.log(str); // Returns 5+ QUESTION_2

matches = re.exec(str);
console.log(matches); // Returns a match on NULL - doesn't find QUESTION_2
re2 = new RegExp("( |^)(" + matches[2] + ")( |$)", "g");
str = str.replace(re2, rep);
console.log(str); // Returns 5+ QUESTION_2



问题




  • 为什么第二个匹配总是为空?

  • jsfiddle 可在此处找到。

  • Question

    • Why is the second match always null?
    • The jsfiddle is available here.
    • 推荐答案

      因为你在exec中使用全局标志调用regex引擎会记住lastIndex,它是正则表达式的读/写整数属性,指定开始下一个匹配的索引。

      Since you're using global flag in exec call regex engine remembers lastIndex which is is a read/write integer property of regular expressions that specifies the index at which to start the next match.

      将其置于重置位置:

      re.lastIndex=0;
      

      在下次调用RegExp.exec之前

      Just before next call to RegExp.exec

      re.lastIndex = 0 允许您重置搜索索引以从头开始执行第二次搜索。没有它,搜索从最后一个匹配的索引开始,在这种情况下将产生 null

      re.lastIndex = 0 allows you to reset the search index to perform a second search starting from the beginning. Without it, the search begins at the index of the last match, which would yield null in this case.

      阅读此 Mozilla doc 了解更多信息关于此的信息。根据本手册:

      Read this Mozilla doc for more info on this. As per this manual:

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

      This property is set only if the regular expression used the "g" flag to indicate a global search.

      这篇关于Regex.prototype.exec在搜索的第二次迭代时返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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