Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string contains email in c# [closed]

Tags:

c#

regex

email

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 [email protected] if you are interested"

Please help.

like image 691
Tien Avatar asked Oct 27 '25 04:10

Tien


2 Answers

Here's how you can achieve this:

string para =
    " kjqdshfkjsdfh dskjhskqjdfhk qdhjkdhfj kjhfksjdhf [email protected] jjhdjfhsfjjd jhjhjhj [email protected] ";
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+)*");
}
like image 162
BRAHIM Kamel Avatar answered Oct 29 '25 19:10

BRAHIM Kamel


First you split everything based on a whitespace delimiter (email addresses usually don't contain whitespaces):

var tokens = input.Split(" ");

Now you can validate the different tokens. The most easy one would be checking for an @ symbol and progressing from there. You could use an extensive regex, but you might as well just try and send an email to that address and see if it worked. It's a lot easier and doesn't require a 500-character regex.

Alternatively you can follow @Julie's advise and work with the MailAddress class.

As @Chris correctly remarks: an email address with a whitespace is valid if it is contained within quotes. Since it is a very uncommon edgecase, I would still hang on to this method and add a specific check to your code that validates the combination of quotes and whitespaces.

like image 29
Jeroen Vannevel Avatar answered Oct 29 '25 18:10

Jeroen Vannevel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!