Regex Email validation

c#, regex, validation

Solution

TLD's like .museum aren't matched this way, and there are a few other long TLD's. Also, you can validate email addresses using the MailAddress class as Microsoft explains here in a note:

Instead of using a regular expression to validate an email address, you can use the System.Net.Mail.MailAddress class. To determine whether an email address is valid, pass the email address to the MailAddress.MailAddress(String) class constructor.

public bool IsValid(string emailaddress)
{
    try
    {
        MailAddress m = new MailAddress(emailaddress);

        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

This saves you a lot af headaches because you don't have to write (or try to understand someone else's) regex.

EDIT: For those who are allergic to try/catch: In .NET 5 you can use `MailAddress.TryCreate`. See also https://stackoverflow.com/a/68198658, including an example how to fix .., spaces, missing .TLD, etc.

Problem

I use this ``` @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" ``` regexp to validate the email `([\w\.\-]+)` - this is for the first-level domain (many letters and numbers, also point and hyphen) `([\w\-]+)` - this is for second-level domain `((\.(\w){2,3})+)` - and this is for other level domains(from 3 to infinity) which includes a point and 2 or 3 literals what's wrong with this regex? EDIT:it doesn't match the "something@someth.ing" email

Original source

Related problems