简体   繁体   English

Javascript 正则表达式测试方法奇怪的行为

[英]Javascript Regexp test method weird behaviour

I've been trying evaluate a string based in a regular expression, however I noticed a weird behaviour and when I test with the regular expression more than once.我一直在尝试基于正则表达式评估字符串,但是我注意到一个奇怪的行为,并且当我多次使用正则表达式进行测试时。 The test method alternates between true and false.测试方法在真假之间交替。 Check this codepen --> http://codepen.io/gpincheiraa/pen/BoXrEz?editors=001检查这个codepen--> http://codepen.io/gpincheiraa/pen/BoXrEz?editors=001

var emailRegex = /^([a-zA-Z0-9_\.\-]){0,100}\@(([a-zA-Z0-9\-]){0,100}\.)+([a-zA-Z0-9]{2,4})+$/,
  phoneChileanRegex = /^\+56\S*\s*9\S*\s*\d{8}(?!\@\w+)/g,
   number = "+56982249953";

if(!number.match(phoneChileanRegex)  && !number.match(emailRegex) ) {
  console.log("it's not a phone number or email address");
}

//Weird Behaviour
console.log(phoneChileanRegex.test(number)); --> true
console.log(phoneChileanRegex.test(number)); --> false

From the MDN documentation : MDN文档中

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() (或与其结合使用)一样,在同一全局正则表达式实例上多次调用的test()将前进到先前的匹配。

So, the second time you call the method, it will look for a match after the first match, ie after +56982249953 . 因此,第二次调用该方法时,它将在第一个匹配项之后(即+56982249953之后) +56982249953匹配+56982249953 There is no match because the pattern is anchored to the start of the string ( ^ ) (and because there are no characters left), so it returns false . 之所以没有匹配,是因为该模式已锚定到字符串( ^ )的开头(并且没有剩余的字符),因此它返回false

To make this work you have to remove the g modifier. 为此,您必须删除g修饰符。

That's because the test method, like many RegExp methods, tries to find multiple matches in the same string when used with the g flag. 这是因为test方法与许多RegExp方法一样,在与g标志一起使用时会尝试在同一字符串中查找多个匹配项。 To do this, it keeps track of position it should search from in the RegExp's lastIndex property. 为此,它在RegExp的lastIndex属性中跟踪应从中搜索的位置。 If you don't need to find multiple matches, just don't put the g flag. 如果您不需要查找多个匹配项,则不必放置g标志。 And if you ever want to use it, just remember to set regex.lastIndex to 0 when you want to test a new string. 而且,如果您要使用它,只需记住要测试新字符串时将regex.lastIndex设置为0。

Read more about lastIndex on MDN 阅读有关MDN的lastIndex更多信息

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

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