BFjamsec
4/18/2018 - 12:04 PM

Extract all email addresses from text

internal static class MailExtractor
{
    public static List<string> ExtractEmails(string data)
    {
        List<string> ExtractedEmailAddresses = new List<string>();

        //instantiate with this pattern
        string EmailPattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
        Regex emailRegex = new Regex(EmailPattern, RegexOptions.IgnoreCase);
        //find items that matches with our pattern
        MatchCollection emailMatches = emailRegex.Matches(data);

        foreach (Match emailMatch in emailMatches)
        {
            ExtractedEmailAddresses.Add(emailMatch.Value);
        }

        return ExtractedEmailAddresses.Distinct().ToList();
    }
}