How to check if string contains email in c#

c#, email, regex

Solution

Here's how you can achieve this:

string para =
    " kjqdshfkjsdfh dskjhskqjdfhk qdhjkdhfj kjhfksjdhf jhjhjhjh@hhhh.com jjhdjfhsfjjd jhjhjhj jkhjhdfjhdjdf@.com ";
var splittedText = para.Split(new char[] {' '});
var mails = splittedText.Where(s => s.Contains("@"));
foreach (var mail in mails)
{
    //here are all your mails  
}

And then validate using the following method:

private bool IsEmailValid(string mail)
{
    try
    {                
        MailAddress eMailAddress = new MailAddress(mail);
        return true;
    }
    catch (FormatException)
    {
        return false;  
    }
}

Or just use something like:

public static bool ValidateEmail(string str)
{                       
    return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}

Problem

It's not hard to do a email validation on a user entered textbox. But this time I would to check if a string/paragraph contains email addresses For example. I would like to check if there is email in the following string "How are you today, please email me at abc@def.com if you are interested" Please help.

Original source

Related problems