gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:48 27 4
gpt4 key购买 nike

我一直在尝试评估基于正则表达式的字符串,但是当我多次使用正则表达式进行测试时,我注意到了一个奇怪的行为。测试方法在 true 和 false 之间交替。检查这个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 documentation :

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

要完成这项工作,您必须删除 g 修饰符。

关于Javascript 正则表达式测试方法奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034770/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com