Parsing dates from string - regex

时间秒杀一切 提交于 2019-12-25 02:40:28

问题


I'm terible with regex and I can't seem to wrap my head around this simple task.

I need to parse out the two dates in a string which always has one of two formats:

"Inquiry at your property for December 29, 2013 - January 03, 2014"

OR

"Inquiry at your property for 29 December , 2013 - 03 January, 2014"

the 2 different date formats are throwing me off. Any insights would be appreciated!


回答1:


/(\d+ \w+, \d+|\w+ \d+, \d+)/ for example. Try it out on Rubular.

For sure, it would pickup more stuff, like 2013 NotReallyAMonth, 12345. But if you don't have things in the input that look like a date, but not actually a date this might work.

You could make the regexp stronger, but applying more restrictions on what is matched:

/(\d{2} (?:January|December), \d{4}|(?:January|December) \d{2}, \d{4})/

In this case the day is always two digits, the year is 4. Months are listed explicitly (you would have to list all of them).

Update: For ranges it would be a different regexp:

/((?:Jan|Dec) \d+ - \d+, \d{4})/

Obviously they can all be combined together:

/(\d{2} (?:January|December), \d{4}|(?:January|December) \d{2}, \d{4}|(?:Jan|Dec) \d+ - \d+, \d{4})/


来源:https://stackoverflow.com/questions/19548809/parsing-dates-from-string-regex

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