1

根据RFC5322和以下验证电子邮件 ID

https://en.wikipedia.org/wiki/Email_address

下面是使用 java 和正则表达式来验证电子邮件 ID 的示例代码。

public void checkValid() {
    List<String> emails = new ArrayList();
    //Valid Email Ids
    emails.add("simple@example.com");
    emails.add("very.common@example.com");                   
    emails.add("disposable.style.email.with+symbol@example.com");
    emails.add("other.email-with-hyphen@example.com");
    emails.add("fully-qualified-domain@example.com");
    emails.add("user.name+tag+sorting@example.com");
    emails.add("fully-qualified-domain@example.com");
    emails.add("x@example.com");
    emails.add("carlosd'intino@arnet.com.ar");
    emails.add("example-indeed@strange-example.com");
    emails.add("admin@mailserver1");
    emails.add("example@s.example");
    emails.add("\" \"@example.org");
    emails.add("\"john..doe\"@example.org");

    //Invalid emails Ids
    emails.add("Abc.example.com");
    emails.add("A@b@c@example.com");
    emails.add("a\"b(c)d,e:f;g<h>i[j\\k]l@example.com");
    emails.add("just\"not\"right@example.com");
    emails.add("this is\"not\\allowed@example.com");
    emails.add("this\\ still\"not\\allowed@example.com");
                    emails.add("1234567890123456789012345678901234567890123456789012345678901234+x@example.com");
    emails.add("john..doe@example.com");
    emails.add("john.doe@example..com");

    String regex = "^[a-zA-Z0-9_!#$%&'*+/=? \\\"`{|}~^.-]+@[a-zA-Z0-9.-]+$";

    Pattern pattern = Pattern.compile(regex);
    int i=0;
    for(String email : emails){
        Matcher matcher = pattern.matcher(email);
        System.out.println(++i +"."+email +" : "+ matcher.matches());
    }
}

实际输出:

   1.simple@example.com : true
   2.very.common@example.com : true
   3.disposable.style.email.with+symbol@example.com : true
   4.other.email-with-hyphen@example.com : true
   5.fully-qualified-domain@example.com : true
   6.user.name+tag+sorting@example.com : true
   7.fully-qualified-domain@example.com : true
   8.x@example.com : true
   9.carlosd'intino@arnet.com.ar : true
   10.example-indeed@strange-example.com : true
   11.admin@mailserver1 : true
   12.example@s.example : true
   13." "@example.org : true
   14."john..doe"@example.org : true
   15.Abc.example.com : false
   16.A@b@c@example.com : false
   17.a"b(c)d,e:f;g<h>i[j\k]l@example.com : false
   18.just"not"right@example.com : true
   19.this is"not\allowed@example.com : false
   20.this\ still"not\allowed@example.com : false
   21.1234567890123456789012345678901234567890123456789012345678901234+x@example.com    : true
   22.john..doe@example.com : true
   23.john.doe@example..com : true

预期输出:

1.simple@example.com : true
2.very.common@example.com : true
3.disposable.style.email.with+symbol@example.com : true
4.other.email-with-hyphen@example.com : true
5.fully-qualified-domain@example.com : true
6.user.name+tag+sorting@example.com : true
7.fully-qualified-domain@example.com : true
8.x@example.com : true
9.carlosd'intino@arnet.com.ar : true
10.example-indeed@strange-example.com : true
11.admin@mailserver1 : true
12.example@s.example : true
13." "@example.org : true
14."john..doe"@example.org : true
15.Abc.example.com : false
16.A@b@c@example.com : false
17.a"b(c)d,e:f;g<h>i[j\k]l@example.com : false
18.just"not"right@example.com : false
19.this is"not\allowed@example.com : false
20.this\ still"not\allowed@example.com : false
21.1234567890123456789012345678901234567890123456789012345678901234+x@example.com : false
22.john..doe@example.com : false
23.john.doe@example..com : false

如何更改我的正则表达式,使其使以下电子邮件 ID 模式无效。

1234567890123456789012345678901234567890123456789012345678901234+x@example.com
john..doe@example.com
john.doe@example..com 
just"not"right@example.com

以下是正则表达式的标准:

局部

电子邮件地址的本地部分可以使用以下任何 ASCII 字符:

  1. 大写和小写拉丁字母A to Za to z
  2. 数字0 to 9;
  3. 特殊字符 !#$%&'*+-/=?^_`{|}~
  4. dot .,前提是它不是第一个或最后一个字符,除非被引用,并且它不连续出现,除非被引用(例如John..Doe@example.com,不允许但 "John..Doe"@example.com允许);
  5. space"(),:;<>@[\]字符是有限制的(它们只允许在带引号的字符串中,如下文所述,此外,反斜杠或双引号必须以反斜杠开头);允许在本地部分的任一端带括号的注释;例如 john.smith(comment)@example.com(comment)john.smith@example.com都等价于 john.smith@example.com

领域

  1. 大写和小写拉丁字母A to Za to z
  2. 数字0 to 9,前提是顶级域名不是全数字的;
  3. hyphen -,前提是它不是第一个或最后一个字符。域和本地部分都允许评论;例如john.smith@(comment)example.comjohn.smith@example.com(comment)等价于 john.smith@example.com
4

3 回答 3

4

It's not the question you asked, but why re-invent the wheel?

Apache commons has a class that covers this already.

org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email)

This way you aren't responsible for keeping up to date with changing email format standards.

于 2018-11-17T00:41:41.847 回答
3

正则表达式是验证电子邮件地址最困难且最容易出错的方法。如果您正在使用 的实现javax.mail来发送电子邮件,那么确定它是否可以工作的最简单方法是使用提供的解析器,因为电子邮件是否兼容,如果库不能使用它,那么它不会事情。

public static boolean validateEmail(String address) {
    try {
        // if this fails, the mail library can't send emails to this address
        InternetAddress ia = new InternetAddress(address, true);
        return ia.isGroup() && ia.getAddress().charAt(0) != '@';
    }
    catch (Throwable t) {
        return false;
    }
}

在严格解析时调用它false允许没有部分的电子邮件。@domain而且由于checkAddress内部调用的函数是私有的,我们不能只调用checkAddress(addr,false,true),因为我们不想要路由信息(实际上是为通过服务器反弹而设计的欺诈功能),我们必须检查验证地址的第一个字母。

现在您可能会注意到,这种验证方法实际上符合 RFC 2822,而不是 5822。原因是除非您实现自己的 SMTP 发件人库,否则您使用的是依赖于这个的,如果您的地址是 5822-valid 但 2822-invalid,那么您的 5822-validation 将变得无用。但是如果你正在实现自己的 5822 SMTP 库,那么你应该学习现有的并编写解析器函数,而不是正则表达式。

于 2018-11-16T13:59:04.260 回答
2

您可以像这样使用 RFC5322
参考正则表达式已修改

"(?im)^(?=.{1,64}@)(?:(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"@)|((?:[0-9a-z](?:\\.(?!\\.)|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)?[0-9a-z]@))(?=.{1,255}$)(?:(\\[(?:\\d{1,3}\\.){3}\\d{1,3}\\])|((?:(?=.{1,63}\\.)[0-9a-z][-\\w]*[0-9a-z]*\\.)+[a-z0-9][\\-a-z0-9]{0,22}[a-z0-9])|((?=.{1,63}$)[0-9a-z][-\\w]*))$"  

https://regex101.com/r/ObS3QZ/1

 # (?im)^(?=.{1,64}@)(?:("[^"\\]*(?:\\.[^"\\]*)*"@)|((?:[0-9a-z](?:\.(?!\.)|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)?[0-9a-z]@))(?=.{1,255}$)(?:(\[(?:\d{1,3}\.){3}\d{1,3}\])|((?:(?=.{1,63}\.)[0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9])|((?=.{1,63}$)[0-9a-z][-\w]*))$

 # Note - remove all comments '(comments)' before runninig this regex
 # Find  \([^)]*\)  replace with nothing

 (?im)                                     # Case insensitive
 ^                                         # BOS

                                           # Local part
 (?= .{1,64} @ )                           # 64 max chars
 (?:
      (                                         # (1 start), Quoted
           " [^"\\]* 
           (?: \\ . [^"\\]* )*
           "
           @
      )                                         # (1 end)
   |                                          # or, 
      (                                         # (2 start), Non-quoted
           (?:
                [0-9a-z] 
                (?:
                     \.
                     (?! \. )
                  |                                          # or, 
                     [-!#\$%&'\*\+/=\?\^`\{\}\|~\w] 
                )*
           )?
           [0-9a-z] 
           @
      )                                         # (2 end)
 )
                                           # Domain part
 (?= .{1,255} $ )                          # 255 max chars
 (?:
      (                                         # (3 start), IP
           \[
           (?: \d{1,3} \. ){3}
           \d{1,3} \]
      )                                         # (3 end)
   |                                          # or,   
      (                                         # (4 start), Others
           (?:                                       # Labels (63 max chars each)
                (?= .{1,63} \. )
                [0-9a-z] [-\w]* [0-9a-z]* 
                \.
           )+
           [a-z0-9] [\-a-z0-9]{0,22} [a-z0-9] 
      )                                         # (4 end)
   |                                          # or,
      (                                         # (5 start), Localdomain
           (?= .{1,63} $ )
           [0-9a-z] [-\w]* 
      )                                         # (5 end)
 )
 $                                         # EOS

How make sudhansu_@gmail.com this as valid email ID – Mihir Feb 7 at 9:34

我认为规范希望本地部分要么用引号括起来
,要么用 [0-9a-z].

但是,要绕过后者并使其sudhansu_@gmail.com生效,只需
将第 2 组替换为:

      (                             # (2 start), Non-quoted
           [0-9a-z] 
           (?:
                \.
                (?! \. )
             |                              # or, 
                [-!#\$%&'\*\+/=\?\^`\{\}\|~\w] 
           )*
           @

      )                             # (2 end)

新的正则表达式

"(?im)^(?=.{1,64}@)(?:(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"@)|([0-9a-z](?:\\.(?!\\.)|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*@))(?=.{1,255}$)(?:(\\[(?:\\d{1,3}\\.){3}\\d{1,3}\\])|((?:(?=.{1,63}\\.)[0-9a-z][-\\w]*[0-9a-z]*\\.)+[a-z0-9][\\-a-z0-9]{0,22}[a-z0-9])|((?=.{1,63}$)[0-9a-z][-\\w]*))$"

新演示

https://regex101.com/r/ObS3QZ/5

于 2018-11-19T20:23:08.350 回答