首页 > 解决方案 > 用于电子邮件验证的正则表达式不允许零件的所有数字

问题描述

我在使用正则表达式进行模型电子邮件验证时遇到问题,我使用以下代码:

^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$-->(https://emailregex.com/)

我将修改为:

123@123.com --> invalid(if before @ all number or after @ all number)
123a@123a.com --> valid(if before @ must combine string or only string and after @ combine string or only string)

任何人改进我的代码,非常感谢。

标签: javascriptregex

解决方案


向您的正则表达式添加负前瞻应该可以做到:

const regex = /^(?!\d+@)\w+([-+.']\w+)*@(?!\d+\.)\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
[ 'a@b.com',
  'a123@b123.com',
  '123@b.com',
  'a@123.com'
].forEach(str => {
  console.log(str + ' ==> ' + regex.test(str));
});

输出:

a@b.com ==> true
a123@b123.com ==> true
123@b.com ==> false
a@123.com ==> false

解释:

  • 第一次前瞻^(?!\d+@):从开始到不是 1+ 位@
  • 第二个前瞻:从下一个点@(?!\d+\.)不是 1+ 位@
  • 如果需要,您可以在之后为标点符号和单词序列添加额外的前瞻

推荐阅读