Wednesday 2 January 2013

Extract All Email Address from a String

Extract All Email Address from a String

Make Use of the Following Function to achieve this:

public static void emas(string text)
 const string MatchEmailPattern =
 + @"((([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])\.

 + @"([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)


Alternatively,You can Use this fuction as well:

using System.IO;
using System.Text.RegularExpressions;
using System.Text;

class MailExtracter

    public static void ExtractEmails(string inFilePath, string outFilePath)
        string data = File.ReadAllText(inFilePath); //read File 
        //instantiate with this pattern 
      Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
        //find items that matches with our pattern
        MatchCollection emailMatches = emailRegex.Matches(data);

        StringBuilder sb = new StringBuilder();

        foreach (Match emailMatch in emailMatches)
        //store to file
        File.WriteAllText(outFilePath, sb.ToString());

No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top