简体   繁体   English

Java中电子邮件验证的正则表达式

[英]regular expression for email validation in Java

I am using the follwoing regular expression我正在使用以下正则表达式

(".+@.+\\.[a-z]+")

Bit it accepts #@#.com as a valid email.位它接受#@#.com 作为有效的电子邮件。 What's the pattern I should use?我应该使用什么模式?

You should use apache-commons email validator.您应该使用 apache-commons 电子邮件验证器。 You can get the jar file from here .您可以从这里获取 jar 文件。

Here is a simple example of how to use it:这是一个如何使用它的简单示例:

import org.apache.commons.validator.routines.EmailValidator;

boolean isValidEmail = EmailValidator.getInstance().isValid(emailAddress);

Here's a web page that explains that better than I can: http://www.regular-expressions.info/email.html ( EDIT : that appears to be a bit out of date since it refers to RFC 2822, which has been superseded by RFC 5322)这是一个比我能解释得更好的网页: http ://www.regular-expressions.info/email.html(编辑:这似乎有点过时,因为它指的是已被取代的 RFC 2822由 RFC 5322)

And another with an interesting take on the problem of validation: http://www.markussipila.info/pub/emailvalidator.php另一个对验证问题有一个有趣的看法:http: //www.markussipila.info/pub/emailvalidator.php

Generally the best strategy for validating an email address is to just try sending mail to it.通常,验证电子邮件地址的最佳策略是尝试向其发送邮件。

[A-Z0-9._%+-]+@[A-Z0-9.-]+.[AZ]{2,4}

If somebody wants to enter non-existent email address he'll do it whatever format validation you choose.如果有人想输入不存在的电子邮件地址,无论您选择什么格式验证,他都会这样做。

The only way to check that user owns email he entered is to send confirmation (or activation) link to that address and ask user to click it.检查用户是否拥有他输入的电子邮件的唯一方法是将确认(或激活)链接发送到该地址并要求用户单击它。

So don't try to make life of your users harder.因此,不要试图让用户的生活变得更加艰难。 Checking for presence of @ is good enough.检查@的存在就足够了。

我通常使用以下一种:

([a-zA-Z0-9]+(?:[._+-][a-zA-Z0-9]+)*)@([a-zA-Z0-9]+(?:[.-][a-zA-Z0-9]+)*[.][a-zA-Z]{2,})
import java.util.regex.*;

class ValidateEmailPhone{

    public static void main(String args[]){

        //phone no validation starts with 9 and of 10 digit
        System.out.println(Pattern.matches("[9]{1}[0-9]{9}", "9999999999"));

        //email validation
        System.out.println(Pattern.matches("[a-zA-Z0-9]{1,}[@]{1}[a-z]{5,}[.]{1}+[a-z]{3}", "abcd@gmail.com"));
    }
}

This is my regex for email validation:这是我用于电子邮件验证的正则表达式:

(([a-zA-Z0-9]+)([\.\-_]?)([a-zA-Z0-9]+)([\.\-_]?)([a-zA-Z0-9]+)?)(@)([a-zA-Z]+.[A-Za-z]+\.?([a-zA-Z0-9]+)\.?([a-zA-Z0-9]+))

For username it allows ".", "_", "-" for separators.对于用户名,它允许使用“.”、“_”、“-”作为分隔符。 After "@" allows only "." “@”之后只允许“.” and "-".和 ”-”。 Can be easy modified for more words.可以很容易地修改更多的单词。

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

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