extraire toutes les adresses e-mail d'un texte en utilisant c#
Existe-t-il un moyen d'extraire toutes les adresses e-mail d'un texte brut en utilisant C# .
Par exemple
Mon adresse e-mail est mrrame@gmail.com et son email est mrgar@yahoo.com
Devrait retourner
Mrrame@gmail.com, mrgar@yahoo.com
J'ai essayé ce qui suit, mais il correspond uniquement aux e-mails parfaits.
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;
}
5 réponses
Vérifiez cet extrait
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());
}
}
Travaux suivants
public static void emas(string text)
{
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})";
Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
int noOfMatches = matches.Count;
// Report on each match.
foreach (Match match in matches)
{
Console.WriteLine(match.Value.ToString());
}
}
Supprimez simplement le " ^ "du début et le" $ " de la fin de votre chaîne de filtre.
Donner à ceci un essai http://www.regular-expressions.info/email.html
Si vous ne voulez pas qu'il corresponde à des adresses e-mail parfaites, n'utilisez pas d'expression régulière qui correspond à des adresses e-mail parfaites.
L'expression régulière que vous utilisez correspondra au début de la ligne ( ^ ) et à la fin de la ligne ( $ ), donc si vous les supprimez, elle ne filtrera pas avec elles.