Regex for matching multiple date formats

时间秒杀一切 提交于 2020-01-03 18:43:07

问题


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.


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/2794069/regex-for-matching-multiple-date-formats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!