JulianJulianov

09.RegularExpressionsExercise-Extract Emails

May 16th, 2020
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.98 KB | None | 0 0
  1. 06. *Extract Emails
  2. Write a program to extract all email addresses from a given text. The text comes at the only input line. Print the emails on the console, each at a separate line. Emails are considered to be in format <user>@<host>, where:
  3. <user> is a sequence of letters and digits, where '.', '-' and '_' can appear between them.
  4. o   Examples of valid users: "stephan", "mike03", "s.johnson", "st_steward", "softuni-bulgaria", "12345".
  5. o   Examples of invalid users: ''--123", ".....", "nakov_-", "_steve", ".info".
  6. • <host> is a sequence of at least two words, separated by dots '.'. Each word is sequence of letters and can have hyphens '-' between the letters.
  7. o   Examples of hosts: "softuni.bg", "software-university.com", "intoprogramming.info", "mail.softuni.org".
  8. o   Examples of invalid hosts: "helloworld", ".unknown.soft.", "invalid-host-", "invalid-".
  9. • Examples of invalid emails: [email protected], …@mail.bg, [email protected], [email protected], mike@helloworld, [email protected]., s.johnson@invalid-.
  10. Examples
  11. Input                                                  Output
  12. Please contact us at: [email protected].              [email protected]
  13.  
  14. Just send email to [email protected] and                [email protected]
  15. [email protected] for more information.             [email protected]
  16.  
  17. Many users @ SoftUni confuse email addresses.          [email protected]
  18. We @ Softuni.BG provide high-quality
  19. training @ homeor @ class. –- [email protected].   
  20.  
  21. using System;
  22. using System.Text.RegularExpressions;
  23.  
  24. public class Program
  25. {
  26.     public static void Main()
  27.     {//(?<=\s|^) - означава да търси съвпадения след всички видове празен интервал(\s) или(|) да съвпада с началната позиция в низа(^).
  28.     //'^' - този символ е отрицание само в [^...] скоби, а в останалите случаи е съвпадение с началната позиция в низ!
  29.     //За съвпадение в крайната позиция на низ се използва '$'!
  30.     //Може да се търсят съвпадения и след края на имейла с (?=\.\s|\s), но в случая няма смисъл. (?<=....)текст(?=....) - това е
  31.     //шаблон за търсене на текст разположен между два критерия преди началото и след края на търсения текст!
  32.         var pattern = @"(?<=\s|^)[A-Za-z\d]+((\.|_|-)?[A-Za-z\d]+)*@[A-Za-z]+((-|\.)?[A-za-z]+)*\.[A-Za-z]+";
  33.        var text = Console.ReadLine();
  34.        
  35.        var matchEmails = Regex.Matches(text, pattern);
  36.  
  37.        foreach (Match item in matchEmails)
  38.        {
  39.           Console.WriteLine(item.Value);
  40.        }
  41.     }
  42. }
Add Comment
Please, Sign In to add comment