我在使用正则表达式进行模型电子邮件验证时遇到问题,我使用以下代码:
^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
-> (https://emailregex.com/)
我将修改为:
[email protected] --> invalid(if before @ all number or after @ all number)
[email protected] --> valid(if before @ must combine string or only string and after @ combine string or only string)
任何人都可以改进我的代码,非常感谢。
向您的正则表达式添加负前瞻应做到这一点:
const regex = /^(?!\d+@)\w+([-+.']\w+)*@(?!\d+\.)\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
[ '[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
].forEach(str => {
console.log(str + ' ==> ' + regex.test(str));
});
输出:
[email protected] ==> true
[email protected] ==> true
[email protected] ==> false
[email protected] ==> false
解释:
^(?!\d+@)
:从开始到结束,不得超过1个数字@
@(?!\d+\.)
:从@
下一个点起不是1+个数字本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句