-2

I've seen a few threads on this, and have tried the solutions presented in them, but I can't seem to fix this. I have a regular expression that checks for two dates in mm/dd/yyyy , mm/dd/yyyy format. There can be any number of spaces in between. My expression works on http://regexr.com/, but when I run the code in VS the regex check is always false. Any help would be greatly appreciated!

        var reg = new Regex(@"\d{1,2}\/\d{1,2}\/\d{1,4}[ ]{0,}\,[ ]{0,}\d{1,2}\/\d{1,2}\/\d{1,4}");

        Console.WriteLine("Please enter two dates in dd/mm/yyyy format seperated by a comma");
        string datesIn = Console.ReadLine();

        while (reg.IsMatch(datesIn) != true);
        {
            Console.WriteLine("Sorry, please make sure to enter your dates in dd/mm/yyyy format seperated by a comma.");
            datesIn.Replace(datesIn, Console.ReadLine());
        }

        String[] dates = datesIn.Split(',');

        foreach (var date in dates)
            Console.WriteLine(date.Trim());
        Console.ReadLine();
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

2

I strongly recommend you to let .NET do that job for you, using TryParse

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        var input = "12/10/2012, 12/15/2015";
        String[] dates = input.Split(',');

        if(dates.Length != 2){
            Console.WriteLine("I said 2 dates");
        } else {
            foreach (var date in dates)
            {
                DateTime parsedDate;
                if(DateTime.TryParse(date, new CultureInfo("es"), DateTimeStyles.None, out parsedDate))
                {
                    Console.WriteLine("{0} Perfect!", parsedDate);
                }
                else 
                {
                    Console.WriteLine("{0} Not right sir!", date);
                }
            }
        }

        Console.ReadLine();
    }
}

Source Code: https://dotnetfiddle.net/VGEQuM

hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • Yeah, I think I am going to go with this route instead, I don't know why I didn't search for that. I kind of got stuck on using regex last night and went down the wrong rabbit hole. Thanks! – danteCLRK Jun 08 '17 at 17:46