C#を使用してテキストからすべての電子メールアドレスを抽出する 質問する

C#を使用してテキストからすべての電子メールアドレスを抽出する 質問する

C# を使用してプレーンテキストからすべての電子メール アドレスを抽出する方法はありますか。

例えば

私のメールアドレスは[メールアドレス]彼のメールアドレスは[メールアドレス]

戻るべき

[メールアドレス][メールアドレス]

以下を試しましたが、完全に一致するメールのみでした。

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

ベストアンサー1

このスニペットをチェックしてください

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

おすすめ記事