Wednesday, September 10, 2008

Parsing Emails using Regular Expressions

Using Regular Expressions

Using regular expression we can simply parse valid emails from the given contents.this is mainly used to extract actual email addressess from the to,from,cc and bcc fields.

Implementation(c#)

First import using System.Text.RegularExpressions;

the code is as below

private string ParseEmails(string text)
{
const string emailPattern = @"\w+@\w+\.\w+((\.\w+)*)?";

MatchCollection emails = Regex.Matches(text, emailPattern, RegexOptions.IgnoreCase);
StringBuilder emailString = new StringBuilder();
foreach (Match email in emails)
{
if (emailString.Length ==0)
{
emailString.Append(email.Value);
}
else
{
emailString.Append("," + email.Value);
}
}

return emailString.ToString();
}

1 comments:

Anonymous said...

Visit http://www.foosms.com for sending free sms.. :)