DotNetDevs
DotNetDevs

Reputation: 27

Regex expression for the date format

I need the regex expression that will find/match below formats

1st July 2018 , July 2nd 2018 , 4th March ,2018 (with , and without comma also either dd/mmm/yyyy and mm/dd/yyyy) I have below regular expression , that is working fine here

The regular expression is

(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*?\s+\d{1,2}(?:[a-z]{2})?(?:\s+|,\s*)\d{4}\b

But it is not working with my code , I dont know what I am placing wrong ...

My code is

Regex regex = new Regex(@"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*?\s+\d{1,2}(?:[a-z]2})?(?:\s+|,\s*)\d{4}\b");
Match match = regex.Match(html);
return match.Value;

Also the above expression is responsible for

January 1st, 2020 But I need also 1st January 2020 ..

Upvotes: 0

Views: 649

Answers (1)

Nitin Kinger
Nitin Kinger

Reputation: 31

Here is C# function which matched and return result true or false for all formats you mention, you can add more date format in formats array also

    public bool checkIsValidDateTime(string date)
        {
            var formats = new[] { "dd MMMM yyyy", "MMMM dd yyyy", "dd MMMM ,yyyy", "MMMM dd, yyyy", "d MMMM yyyy", "MMMM d yyyy", "d MMMM ,yyyy", "MMMM d, yyyy" };

            DateTime dt;
        
            var replacements = new[]{
             new{Find="st",Replace=""},
             new{Find="nd",Replace=""},
             new{Find="rd",Replace=""},
             new{Find="th",Replace=""}
              };


            foreach (var set in replacements)
            {
                date = date.Replace(set.Find, set.Replace);
              
            }

            bool isValid = DateTime.TryParseExact(date, formats, null, DateTimeStyles.None, out dt);

            return isValid;
        }
        
        // which return true for following formats
        
            string input = "1st July 2018";
            string input2 = "July 2nd 2018";
            string input3 = "3rd March ,2018";
            string input4 = "January 4th, 2020";
            string input5 = "20th January 2020";


     bool isvalid1 = checkIsValidDateTime(input); // result true
     bool isvalid2 = checkIsValidDateTime(input2); // result true
     bool isvalid3 = checkIsValidDateTime(input3); // result true
     bool isvalid4 = checkIsValidDateTime(input4); // result true
     bool isvalid5 = checkIsValidDateTime(input5); // result true

Upvotes: 1

Related Questions