Advertisement
sylviapsh

Extract Emails From Text

Jan 30th, 2013
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.Collections.Generic;
  4.  
  5. class ExtractEmailsFromText
  6. {
  7.   //Write a program for extracting all email addresses from given text. All substrings that match the format <identifier>@<host>…<domain> should be recognized as emails.
  8.  
  9.   static void Main()
  10.   {
  11.     string text = @"niceandsimple@example.com very.common@example.com a.little.lengthy.but.fine@dept.example.com disposable.style.email.with+symbol@example.com user@[IPv6:2001:db8:1ff::a0b:dbd0] ""much.more unusual""@example.com ""very.unusual.@.unusual.com""@example.com ""very.(),:;<>[]\"".VERY.\""very@\\ \""very\"".unusual""@strange.example.com postbox@com (top-level domains are valid hostnames) admin@mailserver1 (local domain name with no TLD) !#$%&'*+-/=?^_`{}|~@example.org ""()<>[]:,;@\\\""!#$%&'*+-/=?^_`{}| ~.a""@example.org "" ""@example.org (space between the quotes)";
  12.  
  13.     string[] splitText = text.Split(' ');
  14.     List<string> emailsList = new List<string>();
  15.  
  16.     for (int i = 0; i < splitText.Length; i++)
  17.     {
  18.       if (Regex.IsMatch(splitText[i], @"[\w.!#$%&'*=?^_`{|}~""(),:;<>@[\]]{1,64}@[\w]{1,253}"))
  19.       {
  20.         emailsList.Add(splitText[i]);
  21.       }
  22.     }
  23.  
  24.     foreach (string email in emailsList)
  25.     {
  26.       Console.WriteLine(email);
  27.     }
  28.   }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement