In today's article I will show you how you can get or retrieve all the email id present in a given string using cc#.net. Here I have used regular expression to validate the email id and extract from passed string. Here for show the demo I have used a windows application to represent using C#.Net, you can also use in the console application also.
So, for this article first we will create a new windows application and add the two textbox control and a button control on the from.
/// <summary>
/// To get the regex match collection of email
/// </summary>
/// <param name="emailString">string</param>
/// <returns></returns>
private MatchCollection GetEmailCollectionFromString(string emailString)
{
Regex regex = new Regex("[A-Z0-9a-z._%+-]+@[A-Za-z0-9-]+\\.[A-Za-z]{2,64}");
return regex.Matches(emailString);
}
Credit for above Regex: stackoverflow.comIn above code I have created object for Regex class and passed the regular expression for email id. after that I have used Matches function to get the valid email ids. After this creating the function we will create a button click event to add the working code. Please check the below code.
StringBuilder sb = new StringBuilder();
var emailData = GetEmailCollectionFromString(txtEmailString.Text);
foreach (var item in emailData)
{
sb.Append(item + ", ");
}
txtFinalString.Text = sb.ToString();
In above code I have first created the object for StringBuilder class. After that taken a variable and used the function GetEmailCollectionFromString. In this function I have passed the string value from which we want to extract the email id.After getting value I have used foreach loop to read the extracted email ids and append it into the StringBuilder object. Finally, I have assigned the extracted output to the output textbox. Now lets run the code to check the output.
We will add a string which is having some email id in it and an invalid email id. Please check below string having email id.
Place the string in input textbox.This is a sample one email id as email1@gmail.om, second email is email2@yahoo.in, third email id is email3@google.com. So we are having 3 correct email and one wrong which is email4@gmail
Now click on "Extract Email Id" button by placing a break point. As the code execution complete we will see three email ids.