Checking if a string contains a regex in the form of a date in c#

I have a string variable defined as :

string str = Request[columns[2][search]];

Sometimes the str returns me a value of AR and sometimes 15/02/2018 to 23/04/2018

Therefore I am checking if the str contains 15/02/2018 to 23/04/2018, then it should return me true.

To perform this check I have used the below code, which does not seem to work. It always returns me false. Can someone please help me with this or by using a regex as an alternative ?

 DateTime date;

 Boolean isValidDate = DateTime.TryParseExact(str, "dd/MM/yyyy to dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Jon Skeet
people
quotationmark

I would do this in two passes:

  • Use a regular expression to extract the dates if they're present at all.
  • Use DateTime.TryParseExact to check that each date really is a date.

I would recommend against trying to do full date validation in the regular expression itself - that's more in the DateTime domain. The regular expression domain is more "finding the bit of text that might be a date".

Here's a complete example of this approach:

using System;
using System.Globalization;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        Test("AR");
        Test("99/99/9999 to 99/99/9999");
        Test("15/02/2018 to 23/04/2018");
    }

    static void Test(string text)
    {
        var result = TryParseDates(text, out var from, out var to);
        Console.WriteLine(result 
            ? $"{text}: match! From={from:yyyy-MM-dd}; To={to:yyyy-MM-dd}"
            : $"{text}: no match");
    }    

    static readonly Regex dateToDatePattern = new Regex(@"^(\d{2}/\d{2}/\d{4}) to (\d{2}/\d{2}/\d{4})$");

    static bool TryParseDates(string text, out DateTime from, out DateTime to)
    {
        var match = dateToDatePattern.Match(text);
        if (match.Success)
        {
            // Don't assign values to the out parameters until we know they're
            // both valid.
            if (DateTime.TryParseExact(match.Groups[1].Value, "dd/MM/yyyy",
                    CultureInfo.InvariantCulture, DateTimeStyles.None, out var tempFrom)
                &&
                DateTime.TryParseExact(match.Groups[2].Value, "dd/MM/yyyy",
                    CultureInfo.InvariantCulture, DateTimeStyles.None, out var tempTo))
            {
                from = tempFrom;
                to = tempTo;
                return true;
            }
        }
        // Either the regex or the parsing failed. Either way, set
        // the out parameters and return false.
        from = default(DateTime);
        to = default(DateTime);
        return false;
    }
}

Output:

AR: no match
99/99/9999 to 99/99/9999: no match
15/02/2018 to 23/04/2018: match! From=2018-02-15; To=2018-04-23

people

See more on this question at Stackoverflow