Javascript Regexp测试方法奇怪的行为 [英] Javascript Regexp test method weird behaviour
问题描述
我一直在尝试使用正则表达式来评估字符串,但是我注意到了一种奇怪的行为,当我使用正则表达式多次测试时。测试方法在true和false之间交替。
查看此编码器 - > http://codepen.io/gpincheiraa/pen / BoXrEz?editors = 001
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
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
推荐答案
来自 MDN文档:
与
exec()
(或与之结合使用)一样,test()
在同一个全局正则表达式实例上多次调用将超过上一个匹配。
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.
所以,第二次调用方法,它会在第一场比赛后寻找一场比赛,即在 +56982249953
之后。没有匹配,因为模式锚定到字符串的开头( ^
)(并且因为没有剩下的字符),所以它返回 false
。
So, the second time you call the method, it will look for a match after the first match, i.e. after +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
.
要完成这项工作,您必须删除 g
修饰符。
To make this work you have to remove the g
modifier.
这篇关于Javascript Regexp测试方法奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!