开发者

Way to detect if String content is a DateTime - RegExp? [duplicate]

This question already has an answer here: Closed 11 years ago.

Possible Duplicate:

generically parsing String to date

Followin开发者_StackOverflow社区g situation:

I need to detect if a String contains a DateTime/Timestamp. The problem is that those DateTimes come in various formats and granularity such as:

2011-09-12 12-09-2011 12.09.2011 2011-09-01-14:15 ... and many many more variations

I don't need to understand the semantics (e.g. distinct between day or months) I just need to detect let's say 80% of the most common DateTime variations.

My first thought was using RegExp - which I'm far from being familiar with and also I would need to familiarize myselft with all variations in which DateTimes can come.

So my questions:

  • Does anybody know a canned RegExps to achieve this?
  • Is there maybe some Java library that could do this task?

Thanks!!


There is another question of same context, hope that link will help you: Dynamic regex for date time formats


you're going to struggle to find a generic match. For the day - month - year section you could possibly use a pattern like (\d{1,2}.){2}\d{4} which would match dates in format dd*mm*yyyy

DateFormat would be a better choice, I think. As John B suggested above, create a list of valid formats and try to match against each one.


Use Java's DateFormat.

You can set up as many formats as you want and iterate through them looking for a match. You will have to catch exceptions for the formats that don't parse and so this solution is not efficient but will work.

Edit per comment:

If you don't want to have exceptions due to performance the you would need to set up a list of regular expressions (one for each format you will support). Find the regex (if any) that matches your input and convert it to a date based on the matching format. What I would suggest would be to match a DateFormat to each regex and let the appropriate DateFormat do the work of parsing once you have identified the appropriate DateFormat. This would reduce the chance of errors in using the groups from the regex to produce the date. Personally, I don't know if this would actually be more efficient than try/catch so I would opt for the more straightforward mechanism (using DateFormat directly).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜