jasondlee jasondlee - 3 years ago 141
Java Question

Finding 12-hour format Time in a String with Regex in Java

I'm trying to find a time in a String using a regex in Java. Here's the regex:


That should look for 1 or 2 digits, followed by a colon, two more digits, then either "am" or "pm" (irrespective of case).

It mostly works, but if I wrap that entire regex in a capture group, I only get hh:mm. For example, "12:34am" returns just "12:34". No "am".

UPDATE: Full code example

Pattern p = Pattern.compile("\\d{1,2}?:\\d\\d(?)(am|pm)??");
Matcher matcher = p.matcher("12:34AM");
Assert.assertEquals("12:34AM", matcher.group());

Anyone have any idea why?

Answer Source

Instead of your current pattern, you might want to use \b(?:[01]?\d|2[0-3]):[0-5]?\d(?:[ap]m)?\b to match times, with the case-insensitive flag set or even use alternatives to distinct between 24h notation and 12h notation with am/pm

Your current pattern uses a lazy optional pattern to match the am/pm ((am|pm)??), as this is at the end of the pattern, it will never match (except when used in the context of .matches() instead of .find(), as it forces a full match).

I'm honestly not sure about the (?) in your pattern.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download