但是,我尝试使用两个具有逻辑和条件块的RegEx.test()方法,但没有得到预期的结果。
const mobileRegEx = /[0][4-5][0-9]{8}/g;
const firstPhone = '0432779680';
const secondPhone = '0543000987';
if(mobileRegEx.test(firstPhone) && mobileRegEx.test(secondPhone)){
console.log(firstPhone, secondPhone); /* expecting this to be executed but it is not */
}发布于 2022-03-28 02:28:54
带有g (全局)标志的正则表达式跟踪上次匹配的位置,并从下一个位置继续搜索。
因此,这意味着第一次比赛将返回第一个号码上的位置,然后第二次比赛将失败,因为它不是从开始重新开始,而是从第一场比赛的位置开始。
修复方法是简单地从原始表达式中删除g,如下所示
/[0][4-5][0-9]{8}/;不过,我也看到你的表情可能会出现假阳性。例如,如果在实际数字之前和之后添加随机字符,则仍然匹配。
例如。
firstPhone = 'WRONG0432779680WRONG';仍将返回真。如果您使用它来验证电话号码格式,则需要将regex限制为传递的整个字符串。您可以在开头使用^,在末尾使用$,这样就可以说这是整个字符串。
所以正则表达式应该看起来像
const mobileRegEx = /^[0][4-5][0-9]{8}$/;这是最后的代码
const mobileRegEx = /^[0][4-5][0-9]{8}$/;
const firstPhone = '0432779680';
const secondPhone = '0543000987';
if(mobileRegEx.test(firstPhone) && mobileRegEx.test(secondPhone)){
console.log(firstPhone, secondPhone);
}
https://stackoverflow.com/questions/71641710
复制相似问题