What should be the regex for matching date of any format like:
26FEB2009
31DEC2009
27 Mar 2008
30 Jul 2009
26-Feb-2009
27-Aug-2009
29/05/2008
07.11.2008
Jan 11 2008
May 26 2008
What should be the regular expression for that?
I have regex that matches with 26-Feb-2009 and 26 FEB 2009 with but not with 26FEB2009 . So if any one know then 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])
The date 26FEB2009 is substring of other string like FUTIDX 26FEB2009 NIFTY 0 and parsed from html page, so I can not set the whitespace or delimiter.
I would advice you against using regex for parsing dates and even strongly against using regex for parsing HTML. For parsing dates you may take a look at the TryParseExact method and for parsing HTML a DOM parser such as 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
}
If it's matching 26 FEB 2009 and not 26FEB2009, sounds like you need to make the whitespace and delimiter character("-" and "/") between each date segment optional.
The + meta character specifies one or more, consider using * (zero or more) for the whitespace.
EDIT
What I meant was, if your regular expression is matching dates with the whitespace/delimiter character, but is not matching the dates without either of them ie 26FEB2009, then it sounds like you're specifying that the whitespace/delimiter be compulsory for a 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's not missing certain features that you want, but it matches all of your examples.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.