Wednesday, October 8, 2008

Java Regular Expressions for Time Format Matching

Java Regular Expressions for Determining if a String looks like a time: This one will match 1pm, 1:00pm, 12:00 AM, 00:01.00010101
"\\s*[0-9][0-9]?\\s*(\\:\\s*[0-9][0-9]\\s*(\\.[0-9]+\\s*)?([a|p|A|P][m|M])?|([a|p|A|P][m|M])?)\\s*"
This one will match 1:00pm, 12:00 AM
"\\s*[0-9][0-9]?\\:[0-9][0-9]?\\s*([a|p|A|P][m|M])?\\s*"
(If you need one that can handle timezone at end, you're on your own.) The code to match is:
            Pattern timePattern = Pattern.compile(EXPRESSION_GOES_HERE);
            Matcher timePatternMatcher = timePattern.matcher("1:00");
            if (timePatternMatcher.matches()) {
                ...
            }
Even though I have tried a few OS X regexp widgets and other online tools, they weren't as helpful as the Java regular expression online tester tool by fileformat.info which was awesome!! The goal was to avoid parsing a string as a date when it was a time or vice versa because doing that would throw an exception, and I like to avoid exceptions when possible. However, the pattern matching may incur more overhead than plain old try { result = (Date)formatter.parse(datetime.trim()); } catch (ParseException pe) { log.error("...", pe); }. If you're interested in learning more about Java Regular Expressions, look at Lesson: Regular Expressions (The Java™ Tutorials > Essential Classes).

No comments: