Matching a valid date
We will create a regex to validate a date pattern of yyyy-mm-dd, yyyy/mm/dd, or yyyy.mm.dd. At first, the regex will look daunting, but bear with me. When you have completed the code and run the application, we will dissect the regex. Hopefully, the expression logic will become clear.
Getting ready
Ensure that you have added the correct assembly to your class. At the top of your code file, add the following line of code if you haven't already done so:
using System.Text.RegularExpressions;
How to do it…
Create a new method called
ValidDate()
that takes a string as the parameter. This string will be the date pattern we want to validate:public void ValidDate(string stringToMatch) { }
Add the following regex pattern to your method, to a variable in the method:
string pattern = $@"^(19|20)\d\d[-./](0[1-9]|1[0-2])[- ./](0[1-9]|[12][0-9]|3[01])$";
Finally, add the regex to match the supplied string parameter:
if (Regex.IsMatch(stringToMatch, pattern)) Console.WriteLine($"The string...