javascript - 用于电子邮件验证的正则表达式不允许零件的所有数字
问题描述
我在使用正则表达式进行模型电子邮件验证时遇到问题,我使用以下代码:
^\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)
任何人改进我的代码,非常感谢。
解决方案
向您的正则表达式添加负前瞻应该可以做到:
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+ 位@
- 如果需要,您可以在之后为标点符号和单词序列添加额外的前瞻
推荐阅读
- python - tkinter NavigationToolbar2Tk with matplotlib disappears
- while-loop - ZSH script exits even though ERR_EXIT is off
- python - 检查python中dict中的键值是否相同
- .net - 如何从 Web 应用 (Azure B2C) 调用多个 Web API
- node.js - Mongoose:使用 mongoose 中间件 pre("remove") 将文档复制到另一个
- c++ - 计算机的 USB 端口 ID
- java - 在 Android 上使用 BroadcastReceiver 从 Java 警报执行本机代码
- python - 有没有办法让一个精灵以网格模式跟随另一个精灵?
- python - 使用 Pyinstaller 生成 exe 后 Python (3.8.0) 中的 TCP 协议问题
- html - 使用变量添加类名(HTML、ReactJS)