write a C# method to find email addresses in a body of text and return it as a list
- User
write a C# method to find email addresses in a body of text and return it as a list
Assistant
Email Address Extraction Method in C#
The following C# method uses a regular expression to find email addresses in a given body of text.
using System; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; public class EmailExtractor { /// <summary> /// Extracts email addresses from a given body of text. /// </summary> /// <param name="text">The text to search for email addresses.</param> /// <returns>A list of unique email addresses found in the text.</returns> public static List<string> ExtractEmailAddresses(string text) { // Regular expression pattern to match most common email address formats string emailPattern = @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"; // Use Regex.Matches to find all matches of the pattern in the text MatchCollection matches = Regex.Matches(text, emailPattern); // Convert the matches to a list of unique email addresses return matches.Cast<Match>() .Select(m => m.Value) .Distinct() .ToList(); } public static void Main(string[] args) { string text = "Contact me at john.doe@example.com or jane.smith@example.org for more information."; List<string> emailAddresses = ExtractEmailAddresses(text); Console.WriteLine("Email Addresses:"); foreach (var email in emailAddresses) { Console.WriteLine(email); } } }