javascript - 为什么反转全局正则表达式总是在 JavaScript 中返回 true

标签 javascript regex

示例代码

这如广告所示:

var re = /abc/;
re.test("abc");
//true
!re.test("abc");
//false;

这不是:

var re2 = /abc/g;
//undefined
re2.test("abc");
//true
!re2.test("abc");
//true

什么给了?

我已经用多个正则表达式对其进行了测试,似乎 /g 标志使所有 ! 都返回 true。

如果有帮助,我正在使用 Chrome 34。

最佳答案

来自MDN page on .test() :

Use test() whenever you want to know whether a pattern is found in a string (similar to the String.search method); for more information (but slower execution) use the exec method (similar to the String.match method). As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

因此,使用 g 标志将在每次连续调用 .test() 时移动字符串,前进到它找到的每个匹配项(与 相同的行为.exec()).

它通过修改正则表达式本身的一个名为 lastIndex 的属性来做到这一点,该属性告诉下一个 .test() 操作下次应该从哪里开始搜索字符串使用正则表达式(使用某些方法)。 g 标志告诉正则表达式使用 .lastIndex 属性。如果没有该标志,则不会使用该属性。该属性可以手动设置回 0,但如果您只是删除 g 标志,则不必担心。

除非您明确尝试使用此功能,否则您可能不想将 g 标志与 .test() 一起使用。

关于javascript - 为什么反转全局正则表达式总是在 JavaScript 中返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344220/

相关文章:

javascript - 测试错误 : Component is not part of any NgModule or the module has not been imported into your module

regex - 匹配或没有匹配项时留空

java - 如何验证 DMN camunda 中的输入表达式

java - Java中从行号找出方法名?

java - Rhino 在 Java 中评估 javascript 对象

javascript - 来自 CSS ID 的百分比变量

javascript - 检测到 :first-child support

c++ - 使用 regex.h 进行全词匹配

JavaScript 等价于 php DOMDocument 对象

javascript - 从弹出窗口将 HTML 插入 CKeditor