Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 03. Match Dates
- Write a program, which matches a date in the format “dd{separator}MMM{separator}yyyy”. Use named capturing groups in your regular expression.
- Compose the Regular Expression
- Every valid date has the following characteristics:
- • Always starts with two digits, followed by a separator
- • After that, it has one uppercase and two lowercase letters (e.g. Jan, Mar).
- • After that, it has a separator and exactly 4 digits (for the year).
- • The separator could be either of three things: a period (“.”), a hyphen (“-“) or a forward slash (“/”)
- • 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.
- You can follow the table below to help with composing your RegEx:
- Match ALL of these Match NONE of these
- 13/Jul/1928, 10-Nov-1934, 25.Dec.1937 01/Jan-1951, 23/sept/1973, 1/Feb/2016
- Use named capturing groups for the day, month and year.
- 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.
- using System;
- using System.Text.RegularExpressions;
- using System.Linq;
- public class Program
- {
- public static void Main()
- { //Ака се налага да пиша повтаряща(неименована) група \n се броят без именованите групи , защото сайтовете броят групите,
- //независимо дали е именована или не(карат наред) , а във Visual Studio се броят първо неименованите групи, като винаги
- // нулевата група е целия патерн(Groups[0] = patern)!!!
- //Пример: "Mon-13/Jul/2020-21"
- //var pattern = @"\b("група 3"?<Week>[A-Z][a-z]{2})("група 1"-)("група 4"?<Day>\d{2})("група 2"\/|-|.)("група 5"?<Month>[A-Z][a-z]{2})
- //"тук се повтаря група 2"\2("група 6"?<Year>\d{4})"тук се повтаря група 1"\1("група 7"?<Century>\d{2})\b";
- var pattern = @"\b(?<Day>\d{2})(\/|-|.)(?<Month>[A-Z][a-z]{2})\1(?<Year>\d{4})\b";
- var dates = Console.ReadLine();
- var matchDates = Regex.Matches(dates, pattern);
- foreach (Match date in matchDates)
- {
- var day = date.Groups["Day"].Value;
- var month = date.Groups["Month"].Value;
- var year = date.Groups["Year"].Value;
- Console.WriteLine($"Day: {day}, Month: {month}, Year: {year}");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment