Regular expression for matching date

I have no knowledge of regular expressions except using Regex library in C# , that too with pattern matching expressions searched from net.

I would like to have regex to match date in below two mentioned formats , no need for Year part.

  • 8 October or 8 Oct

  • September 19 or Sep 19

  • Please help me out , searching Google hasn't helped me .


      string Date = "December 8"
    
      MatchCollection MC = Regex.Matches(Date, @"(?i)([d]{1,2}(s)?(January|Jan|February|feb|March|mar|April|Apr|May|June|July|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec))|(January|Jan|February|feb|March|mar|April|Apr|May|June|July|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec)(s)?[d]{1,2}");
    

    Why struggle with regular expressions when the framework already provides you with the TryParseExact method which is designed to do exactly that:

    public class Program
    {
        static void Main()
        {
            var str = "8 October";
            DateTime date;
            var formats = new[] { "d MMMM", "d MMM" };
            if (DateTime.TryParseExact(str, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                Console.WriteLine(date);
            }
            else
            {
                Console.WriteLine("The date was not in one of the 2 supported formats 'd MMMM' orr 'd MMM'");
            }
        }
    }
    

    You could even make it culture aware. For example let's suppose that you have french speaking users of your site that would probably write 8 Octobre instead of 8 October .

    In this case you could specify the current culture or force a specific culture:

    var str = "8 Octobre";
    DateTime date;
    var formats = new[] { "d MMMM", "d MMM" };
    var ci = new CultureInfo("fr-FR");
    if (DateTime.TryParseExact(str, formats, ci, DateTimeStyles.None, out date))
    {
        // use the date instance here
    }
    

    Further reading: custom datetime formats.


    Try this regex:

    (?<month>[a-zA-Z]+)s+(?<day>d+)|(?<day>d+)s+(?<month>[a-zA-Z]+)
    

    and get groups named: day and month

    链接地址: http://www.djcxy.com/p/77030.html

    上一篇: 在SPA中下载文件

    下一篇: 正则表达式匹配日期