Parsing dates from string - regex

2019-09-02 13:07发布

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条回答
啃猪蹄的小仙女
2楼-- · 2019-09-02 13:52

/(\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})/
查看更多
登录 后发表回答