Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a way to extract all email addresses from a plain text using C# .

For example

my email address is mrrame@gmail.com and his email is mrgar@yahoo.com

should return

mrrame@gmail.com, mrgar@yahoo.com

I have tried the following but it matches perfect emails only.

 public 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})$";


        public static bool IsEmail(string email)
        {
            if (email != null) return Regex.IsMatch(email, MatchEmailPattern);
            else return false;
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
419 views
Welcome To Ask or Share your Answers For Others

1 Answer

check this snippet

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+)*",
            RegexOptions.IgnoreCase);
        //find items that matches with our pattern
        MatchCollection emailMatches = emailRegex.Matches(data);

        StringBuilder sb = new StringBuilder();

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...