有没有办法使用 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/