开发者

Regex for matching multiple date formats

开发者 https://www.devze.com 2022-12-30 03:02 出处:网络
What should be the regex for matching date of any format like: 26FEB2009 31DEC2009 27 Mar 2008 30 Jul 2009

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 substri开发者_如何学运维ng 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 i.e 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号