Regular expression for date

What should be a regular expression to match the date of any format, for example

26FEB2009 30 Jul 2009 27 Mar 2008 29/05/2008 27 Aug 2009 

What should be the regular expression for this?

I have a regex that matches February 26th, 2009 and February 26th, 2009 FEB , but not with 26FEB2009 . Therefore, if anyone knows, please update it.

 (?:^|[^\d\w:])(?'day'\d{1,2})(?:-?st\s+|-?th\s+|-?rd\s+|-?nd\s+|-|\s+)(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*(?:\s*,?\s*|-)(?:'?(?'year'\d{2})|(?'year'\d{4}))(?=$|[^\d\w]) 

Date 26FEB2009 is a substring of another string, for example FUTIDX 26FEB2009 NIFTY 0 , and is parsed from an html page, so I can not set a space or a separator.

EDIT Examples:

 07.11.2008 Jan 11 2008 May 26 2008 26FEB2009 27 Mar 2008 
+4
source share
2 answers

If it matches 26 FEB 2009, not 26FEB2009, it sounds like you need to make the space character and separator ("-" and "/") between each date segment optional.

The + symbol indicates one or more, consider using * (zero or more) for spaces.

EDIT

What I meant, if your regular expression matches dates with a space / separator character, but does not match dates without any of them, i.e. 26FEB2009, then it looks like you indicate that a space / separator is mandatory for the match.

Here's something I quickly knocked together:

 (\d{1,2})(\/|-|\s*)?((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|\d{2})(\/|-|\s*)?(\d{4}) 

You might want to check that it does not miss some functions that you want, but it matches all your examples.

+1
source

I would advise you to use regex for parsing dates, and even strongly against using regex for parsing HTML. For parsing, you can take a look at the TryParseExact method and parse the HTML DOM parser, such as the Html Agility Pack :

 var dateStr = "26FEB2009"; var formats = new[] { "ddMMMyyyy", "dd MMM yyyy", "dd/MM/yyyy" }; DateTime date; if (DateTime.TryParseExact( dateStr, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out date)) { // You have a match, use the date object } 
+4
source

Source: https://habr.com/ru/post/1309187/


All Articles