简体   繁体   English

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

[英]Why does inverting a global regex always return true in JavaScript

Sample Code 样例代码

This works as advertised: 如广告所示:

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

This does not: 这不是:

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

What gives? 是什么赋予了?

I've tested it with multiple regex and it seems the /g flag makes all ! 我已经使用多个正则表达式进行了测试,似乎/g标志可以解决所有问题! 's return true. 返回true。

I'm using Chrome 34 if that helps. 如果有帮助,我正在使用Chrome 34。

From the MDN page on .test() : .test()MDN页面上

Use test() whenever you want to know whether a pattern is found in a string (similar to the String.search method); 每当您想知道是否在字符串中找到模式时都使用test()(类似于String.search方法); for more information (but slower execution) use the exec method (similar to the String.match method). 有关更多信息(但执行速度较慢),请使用exec方法(类似于String.match方法)。 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. 与exec(或与exec结合使用)一样,在同一全局正则表达式实例上多次调用的test将前进到先前的匹配。

So, using the g flag will move through the string on each successive call to .test() advancing past each match it finds (same behavior as .exec() ). 因此,使用g标志将在每次对.test()后续调用中在字符串中移动,从而前进到它找到的每个匹配项(与.exec()相同)。

It does this by modifying a property of the regex itself called lastIndex which tells the next .test() operation where it should start searching in the string the next time the regex is used (with certain methods). 它是通过修改正则表达式本身的属性lastIndex来实现的,该属性告诉next .test()操作,下一次使用正则表达式时(在某些方法下)应该在哪里开始搜索字符串。 It is the g flag that tells the regex to use the .lastIndex property. g标志告诉正则表达式使用.lastIndex属性。 Without that flag, that property is not used. 没有该标志,则不使用该属性。 That property can be manually set back to 0 , but if you just remove the g flag, then you don't have to worry about it. 可以将该属性手动设置回0 ,但是如果仅删除g标志,则不必担心它。

Unless you are explicitly trying to use this capability, you probably don't want to use the g flag with .test() . 除非您明确尝试使用此功能,否则可能不希望将g标志与.test()

The first time you call re2.test(), it move a pointer index property called lastIndex to the end of pattern string of re2 object. 第一次调用re2.test()时,它将一个名为lastIndex的指针索引属性移动到re2对象的模式字符串的末尾。 The second time you call it, it will return false because it can not find any match of "abc" after "c" character of pattern string 第二次调用它时,它将返回false,因为在模式字符串的“ c”字符后找不到“ abc”的任何匹配项

After each calling .test(), you can reset it by re2.lastIndex = 0 . 每次调用.test()之后,都可以通过re2.lastIndex = 0对其进行重置。 So the second time you call .test(), it will search from first index 因此,第二次调用.test()时,它将从第一个索引进行搜索

This property only works if the "g" modifier is set. 仅当设置了“ g”修饰符时,此属性才起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM