从文本文件中读取有效的电子邮件地址

本文关键字:有效 电子邮件地址 读取 文本 文件 | 更新日期: 2023-09-27 18:18:48

我有一个纯文本文件。要求是从文本文件中读取有效的电子邮件地址。

文本文件不包含任何特殊字符,每行包含一个单词。

样本

test1
test@yahoo.com
test2
test@gmail.com

我尝试按如下方式读取文本文件,

var emails = File.ReadAllLines(@"foo.txt");

但是找不到如何从文本文件中提取有效的电子邮件。

我正在使用 C# 4.0

从文本文件中读取有效的电子邮件地址

如果只有您的电子邮件行具有@字符,则可以使用

var emails = File.ReadAllLines(@"foo.txt").Where(line => line.Contains("@"));

好吧,我承认。这是我见过的最糟糕的电子邮件验证 :) 让我们更深入。您可以使用MailAddress类来检查您的行。让我们定义一种检查电子邮件地址是否有效的方法;

public bool IsValidMailAddress(string s)
{
    try
    {
        MailAddress m = new MailAddress(s);
        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

然后我们可以使用;

var emails = File.ReadAllLines(@"foo.txt").Where(line => IsValidMailAddress(line));
嗨,

使用正则表达式过滤有效的电子邮件地址。

下面给出了示例代码。

var emails = File.ReadAllLines(@"foo.txt")
                       .Where(x => x.IsValidEmailAddress());
public static class extensionMethods
    {
        public static bool IsValidEmailAddress(this string s)
        {
            Regex regex = new Regex(@"^['w-'.]+@(['w-]+'.)+['w-]{2,4}$");
            return regex.IsMatch(s);
        }
    }

你做对了。 您正在调用ReadAllLines方法,该方法已经返回array。只有你需要做一个foreach循环。如:

var emails = File.ReadAllLines(@"foo.txt");
foreach (var email in emails)
{
    //write validation logic of emails here
}

单击此处以更好地理解。

您可以使用正则表达式来执行此操作。查看此 MSDN 示例作为参考。

摘自MSDN:

   public bool IsValidEmail(string strIn)
   {
       invalid = false;
       if (String.IsNullOrEmpty(strIn))
          return false;
       // Use IdnMapping class to convert Unicode domain names. 
       try {
          strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper,
                                RegexOptions.None, TimeSpan.FromMilliseconds(200));
       }
       catch (RegexMatchTimeoutException) {
         return false;
       }
       if (invalid) 
          return false;
       // Return true if strIn is in valid e-mail format. 
       try {
          return Regex.IsMatch(strIn, 
                @"^(?("")(""[^""]+?""@)|(([0-9a-z](('.(?!'.))|[-!#'$%&''*'+/='?'^`'{'}'|~'w])*)(?<=[0-9a-z])@))" + 
                @"(?('[)('[('d{1,3}'.){3}'d{1,3}'])|(([0-9a-z][-'w]*[0-9a-z]*'.)+[a-z0-9]{2,17}))$", 
                RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
       }  
       catch (RegexMatchTimeoutException) {
          return false;
       }
   }

然后通过以下方式使用它:

 var emails = File.ReadAllLines(@"foo.txt");
 foreach(var line in emails)
 {
     if(IsValidEmail(line))
     { //do something with the valid email
     }
 }

这取决于你所说的有效是什么意思。有些人采用简单的方法,只在字符串中查找"@"和至少一个"."。其他人则进一步进行电子邮件验证,并尝试根据RFC 822验证地址

看起来简单的方法可以满足您的需求。