Shabat Closer

Friday, February 8, 2013

C#: extract all emails from text

simple function to find all email in text.
using :
System.Text.RegularExpression(regex)

public void get_emails(string text) {
const string MatchEmailPattern = @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
@"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."+
@"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"+
@"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
Regex rx = new Regex(MatchEmailPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Find matches.MatchCollection matches = rx.Matches(text);
// Report the number of matches found.int noOfMatches = matches.Count;// Report on each match.
foreach (Match match in matches) {
string email = match.Value.ToString();if (email == "")
continue;
    //do somthing with email variable like.
    //db.insert(email);
}
}

usage:
get_emails("<a href='my@emsil.com'>email2@domain.com</a>");
//found : my@emsil.com , email2@domain.com

No comments:

Post a Comment