JulianJulianov

02.Regular ExpressionsLab-Match Phone Number

Apr 27th, 2020
978
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.42 KB | None | 0 0
  1. 02. Match Phone Number
  2. Write a regular expression to match a valid phone number from Sofia. After you find all valid phones, print them on the console, separated by a comma and a space “, ”.
  3. Compose the Regular Expression
  4. A valid number has the following characteristics:
  5. • It starts with "+359"
  6. • Then, it is followed by the area code (always 2)
  7. • After that, it’s followed by the number itself:
  8. o   The number consists of 7 digits (separated in two groups of 3 and 4 digits respectively).
  9. • The different parts are separated by either a space or a hyphen ('-').
  10. You can use the following RegEx properties to help with the matching:
  11. • Use quantifiers to match a specific number of digits
  12. • Use a capturing group to make sure the delimiter is only one of the allowed characters (space or hyphen) and not a combination of both (e.g. +359 2-111 111 has mixed delimiters, it is invalid). Use a group backreference to achieve this.
  13. Add a word boundary at the end of the match to avoid partial matches (the last example on the right-hand side).
  14. • Ensure that before the '+' sign there is either a space or the beginning of the string.
  15.  
  16. Examples
  17. Input
  18. +359 2 222 2222,359-2-222-2222, +359/2/222/2222, +359-2 222 2222 +359 2-222-2222, +359-2-222-222, +359-2-222-22222 +359-2-222-2222
  19. Output
  20. +359 2 222 2222, +359-2-222-2222
  21.  
  22. using System;
  23. using System.Text.RegularExpressions;
  24. using System.Linq;
  25.  
  26. public class Program
  27. {
  28.     public static void Main()
  29.     {
  30.          var pattern = @"\+359(-| )2\1\d{3}\1\d{4}\b";   // (-| ) може да е без или |, но  се добавят [], т.е. ([- ])
  31.          var phonesNumbers = Console.ReadLine();
  32.  
  33.          var numbersMatches = Regex.Matches(phonesNumbers, pattern);
  34.          //var counter = 0;
  35.          //foreach (Match item in numbersMatches)
  36.          //{
  37.          //    counter++;
  38.          //    if (numbersMatches.Count != counter)
  39.          //    {
  40.          //        Console.Write(item.Value + ", ");
  41.          //    }
  42.          //    else
  43.          //    {
  44.          //        Console.WriteLine(item.Value);
  45.          //    }
  46.          //}            //Чрез Cast<Match>() достъпвам директно без да форийчвам до collection, а чрез Select(x => x.Value) до item
  47.          var matchedPhones = numbersMatches.Cast<Match>().Select(x => x.Value.Trim()).ToArray();
  48.          Console.WriteLine(string.Join(", ", matchedPhones));
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment