从字符串正则表达式解析日期 [英] Parsing dates from string - regex
问题描述
我对于正则表达式非常可怕,我似乎无法绕过这个简单的任务。
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:
查询您的财产2013年12月29日 - 2014年1月3日
"Inquiry at your property for December 29, 2013 - January 03, 2014"
OR
2014年12月29日 - 2014年1月3日您的财产查询
"Inquiry at your property for 29 December , 2013 - 03 January, 2014"
2种不同的日期格式让我失望。任何见解将不胜感激!
the 2 different date formats are throwing me off. Any insights would be appreciated!
推荐答案
/(\d + \w +,\d +例如\w + \d +,\d +)/
。尝试在 Rubular 。
肯定地,它会吸收更多的东西,如 2013 NotReallyAMonth,12345
。但是,如果您的输入中没有看起来像日期的东西,但实际上并不是日期,这可能会起作用。
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})/
在这种情况下,一天总是两位数,一年是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).
更新:对于范围,它将是一个不同的regexp:
Update: For ranges it would be a different regexp:
/((?:Jan|Dec) \d+ - \d+, \d{4})/
显然他们都可以组合在一起:
/(\d{2} (?:January|December), \d{4}|(?:January|December) \d{2}, \d{4}|(?:Jan|Dec) \d+ - \d+, \d{4})/
这篇关于从字符串正则表达式解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!