首页 > 解决方案 > 日期格式的正则表达式

问题描述

我需要将在以下格式中找到/匹配的正则表达式

2018 年 7 月 1 日、2018 年 7 月 2 日、2018 年 3 月 4 日 (带逗号和不带逗号的 dd/mmm/yyyy 和 mm/dd/yyyy)我有以下正则表达式,在这里工作正常

正则表达式是

(?: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

但它不适用于我的代码,我不知道我放错了什么......

我的代码是

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;

上面的表达式也负责

2020 年 1 月 1 日,但我还需要2020 年 1 月 1 日..

标签: c#asp.netregexdate

解决方案


这是 C# 函数,它为您提到的所有格式匹配并返回结果 true 或 false,您也可以在格式数组中添加更多日期格式

    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


推荐阅读