c# - 使用c#从文本中提取所有电子邮件地址

标签 c# .net regex email

有没有办法使用 C# 从纯文本中提取所有电子邮件地址。

例如

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

应该返回

mrrame@gmail.com, mrgar@yahoo.com

我已经尝试了以下但它只匹配完美的电子邮件。

 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;
        }

最佳答案

检查这个片段

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());
    }
}

关于c# - 使用c#从文本中提取所有电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2333835/

相关文章:

c# - 如何在没有 OWIN 的情况下在 .net Framework 中实现 OpenId Provider

c# - 如何在 C# 中将字符串转换为 "Null Terminated Byte Array"?

.net - 如何在命令行窗口中制作文本框?

Java Pattern 类 - 使用哪个正则表达式来从外括号获取字符串?

c# - 使用 C# 发送电子邮件

c# - 比较包含相同枚举类型的枚举值的两个对象

.NET Core 2.1 无法引用 .NET Framework 4.7.2 类库

c# - 使用 LINQ to XML 时避免暴露于 NullReferenceException

Python正则表达式拆分多个匹配项

java - 使用 Java 中的正则表达式验证电子邮件