简体   繁体   English

在Javascript中使用正则表达式验证带有文件夹的电子邮件地址

[英]Validate email address with folder using regex in Javascript

I am writing a regular expression to validate an email address in JavaScript. 我正在写一个正则表达式来验证JavaScript中的电子邮件地址。

/^[a-zA-Z]([\w-\.]{4,29})+@([\w-]+\.)+[a-zA-Z]{2,3}$/

This is working fine. 一切正常。 But there came an additional requirement like " In a GMAIL address we can specify the folder name along with the email id to which the mail will be delivered. For ex. james+office@gmail.com , the mail will be delivered to the folder "office" under james@gmail.com's inbox. 但是还有一个额外的要求,例如“在GMAIL地址中,我们可以指定文件夹名称以及将邮件发送到的电子邮件ID。例如,james+office@gmail.com,邮件将被发送到该文件夹james@gmail.com收件箱下的“办公室”。

So how can I validate that also in the above regex. 因此,如何在上述正则表达式中进行验证。 The Plus symbol is not mandatory but if + is added it should be in between the other characters before @ symbol . 加号不是强制性的,但如果添加+,则应位于@符号之前的其他字符之间

You can simply add the + character inside of your character class and use a negated match before the @ . 您可以简单地在字符类中添加+字符,并在@之前使用取反的匹配项。 Note that I removed the escape sequence from the dot and moved the hyphen as the last character, or else you need to escape it and also implemented the use of the i modifier for case-insensitive matching. 请注意 ,我从点中删除了转义序列,并将连字符移动为最后一个字符,否则您需要对其进行转义,并且还实现了i修饰符用于不区分大小写的匹配。

/^[a-z]([\w.+-]{4,29})[^+]@([\w-]+\.)+[a-z]{2,3}$/i

Live Demo 现场演示

改用这个:

/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i

I tried this RegEx in the desired scenario you required and it worked fine 我在所需的理想情况下尝试了此RegEx,并且效果很好

^([a-zA-Z0-9_\\-\\.\\+]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$

Try it in RegEx Validator RegEx Validator中尝试

Thanks, Hope it helps 谢谢,希望对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM