JulianJulianov

03.Regular ExpressionsLab-Match Dates

Apr 27th, 2020
573
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.69 KB | None | 0 0
  1. 03. Match Dates
  2. Write a program, which matches a date in the format “dd{separator}MMM{separator}yyyy”. Use named capturing groups in your regular expression.
  3. Compose the Regular Expression
  4. Every valid date has the following characteristics:
  5. • Always starts with two digits, followed by a separator
  6. • After that, it has one uppercase and two lowercase letters (e.g. Jan, Mar).
  7. • After that, it has a separator and exactly 4 digits (for the year).
  8. • The separator could be either of three things: a period (.), a hyphen (-) or a forward slash (/)
  9. • The separator needs to be the same for the whole date (e.g. 13.03.2016 is valid, 13.03/2016 is NOT). Use a group backreference to check for this.
  10. You can follow the table below to help with composing your RegEx:
  11. Match ALL of these                                                    Match NONE of these
  12. 13/Jul/1928, 10-Nov-1934, 25.Dec.1937                                 01/Jan-1951, 23/sept/1973, 1/Feb/2016
  13. Use named capturing groups for the day, month and year.
  14. Now it’s time to find all the valid dates in the input and print each date in the following format: “Day: {day}, Month: {month}, Year: {year}”, each on a new line.
  15.  
  16.  
  17. using System;
  18. using System.Text.RegularExpressions;
  19. using System.Linq;
  20.  
  21. public class Program
  22. {
  23.     public static void Main()
  24.     { //Ака се налага да пиша повтаряща(неименована) група \n се броят без именованите групи , защото сайтовете броят групите,
  25.       //независимо дали е именована или не(карат наред) , а във Visual Studio се броят първо неименованите групи, като винаги
  26.       // нулевата група  е целия патерн(Groups[0] = patern)!!!
  27.       //Пример: "Mon-13/Jul/2020-21"
  28.  //var pattern = @"\b("група 3"?<Week>[A-Z][a-z]{2})("група 1"-)("група 4"?<Day>\d{2})("група 2"\/|-|.)("група 5"?<Month>[A-Z][a-z]{2})
  29.       //"тук се повтаря група 2"\2("група 6"?<Year>\d{4})"тук се повтаря група 1"\1("група 7"?<Century>\d{2})\b";
  30.      
  31.  
  32.          var pattern = @"\b(?<Day>\d{2})(\/|-|.)(?<Month>[A-Z][a-z]{2})\1(?<Year>\d{4})\b";
  33.          var dates = Console.ReadLine();
  34.  
  35.          var matchDates = Regex.Matches(dates, pattern);
  36.  
  37.          foreach (Match date in matchDates)
  38.          {
  39.              var day = date.Groups["Day"].Value;
  40.              var month = date.Groups["Month"].Value;
  41.              var year = date.Groups["Year"].Value;
  42.  
  43.              Console.WriteLine($"Day: {day}, Month: {month}, Year: {year}");
  44.          }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment