Regex Email validation

后端 未结 30 902
北海茫月
北海茫月 2020-11-22 12:16

I use this

@\"^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$\"

regexp to validate the email

([\\w\\.\\-]+) - this is f

30条回答
  •  情话喂你
    2020-11-22 12:39

    This does not meet all of the requirements of RFCs 5321 and 5322, but it works with the following definitions.

    @"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
    

    Below is the code

    const String pattern =
       @"^([0-9a-zA-Z]" + //Start with a digit or alphabetical
       @"([\+\-_\.][0-9a-zA-Z]+)*" + // No continuous or ending +-_. chars in email
       @")+" +
       @"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
    
    var validEmails = new[] {
            "ma@hostname.com",
            "ma@hostname.comcom",
            "MA@hostname.coMCom",
            "m.a@hostname.co",
            "m_a1a@hostname.com",
            "ma-a@hostname.com",
            "ma-a@hostname.com.edu",
            "ma-a.aa@hostname.com.edu",
            "ma.h.saraf.onemore@hostname.com.edu",
            "ma12@hostname.com",
            "12@hostname.com",
    };
    var invalidEmails = new[] {
            "Abc.example.com",     // No `@`
            "A@b@c@example.com",   // multiple `@`
            "ma...ma@jjf.co",      // continuous multiple dots in name
            "ma@jjf.c",            // only 1 char in extension
            "ma@jjf..com",         // continuous multiple dots in domain
            "ma@@jjf.com",         // continuous multiple `@`
            "@majjf.com",          // nothing before `@`
            "ma.@jjf.com",         // nothing after `.`
            "ma_@jjf.com",         // nothing after `_`
            "ma_@jjf",             // no domain extension 
            "ma_@jjf.",            // nothing after `_` and .
            "ma@jjf.",             // nothing after `.`
        };
    
    foreach (var str in validEmails)
    {
        Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
    }
    foreach (var str in invalidEmails)
    {
        Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
    }
    

提交回复
热议问题