首页 > 解决方案 > 为什么我的验证电子邮件地址的正则表达式会出现“无需重复”?

问题描述

我正在学习如何使用正则表达式来验证具有以下标准的电子邮件地址:

如果其域扩展名example123.com并且user的值满足以下约束,则user@domain.extension有效:

理想情况下...

re.test(logic@example123.com) --> should return true
re.test(logic_@example123.com) --> should return true
re.test(logic_0@example123.com) --> should return true
re.test(logic2_0@example123.com) --> should return false
re.test(logic_0@gmail.com) --> should return false

到目前为止,我有:const re = /^[a-z]{1,6}[_?][\d?]{0,4}+@[example123\.com]$/ig

我收到一个错误“无需重复”。我已经浏览了其他 stackoverflow 帖子,但仍然无法完全理解为什么我的模式不起作用。

标签: javascriptregexstring

解决方案


\d{0,4}+中,+不能是 的量词{0,4},所以它有“没什么可重复的”。它可能是\d{0,4}\d+

此外,方括号用于字符范围或文字字符。不要在 中使用它们[_?],这将在此处解释为搜索_?

由于您不希望电子邮件中出现大写字母,因此您必须删除i正则表达式中忽略大小写的修饰符。

尝试这个:

const re = /^[a-z]{1,6}_?\d{0,4}@example123\.com$/

console.log(re.test("logic@example123.com"));


推荐阅读