Simple email validation [duplicate]

吃可爱长大的小学妹 提交于 2019-11-29 18:11:28

.+@.+ will match anything, including @, followed by @, followed by anything, including @. Use [^@]+@[^@]+ instead.

Or cease from reinventing the wheel, grab Apache Commons and use its EmailValidator.

You can use the class javax.mail.internet.InternetAddress from the Javamail API (there is a validate method)

This is a solved problem in numerous libraries. Do not reimplement your own.

Getting this 100% correct in regexps is much, much harder than you think it is.

This site suggests that the following pattern matches RFC 5322 and covers most email addresses used today:

Pattern p = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", Pattern.CASE_INSENSITIVE);

It worked for a few quick tests that I made.

Consider storing the compiled pattern in a constant for improved performance.

It should be Pattern p = Pattern.compile(".+@{1}+\\.[a-z]+");

BUT:

This my answer above is wrong exactly like the answer @larsmans, because:

this(comment)me@demo.com is a valid email.

You have to read the RFC: http://tools.ietf.org/html/rfc5322

In fact, use a good library, as apache-commons.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!