Parse Email Addresses From String Using Regular Expression

This static method will parse out email addresses from a string and return a List<T> of strings where each item in the List is a valid email address.

/// <summary>
        /// Iterates through a string of text and parses out email addresses that may exist in that string.
        /// A List of strings will be returned where each string is a valid email address.
        /// </summary>
        /// <param name="stringToParse">The string to parse out email addresses from.</param>
        /// <returns>Returns a List of email addresses.</returns>
        protected static List<string> ParseOutEmails(string stringToParse)
        {
            List<string> emailList = new List<string>();

            Regex reEmail= new Regex(@"[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,5}");

            MatchCollection matches = reEmail.Matches(stringToParse);

            foreach (Match m in matches)
            {
                emailList.Add(m.ToString());
            }

            return (emailList);
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s