jasondlee jasondlee - 1 month ago 8
Java Question

Finding Time in a String with a Regex in Java

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

\d{1,2}?:\d\d(?)(am|pm)??


That should ;) look for 1 or 2 digits, followed 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.assertTrue(matcher.find());
Assert.assertEquals("12:34AM", matcher.group());


Anyone have any idea why?

Answer

Your regex is not correct. I can suggest this one.

\d?\d:\d\d([aA][mM]|[pP][mM])?

You can check it here: https://regex101.com/r/P1o4dS/1

In regard to your regex. The first question mark is unnecessary, because you already specified that a digit can appear once or twice. The second question mark alone in a capturing group is even more confusing. And the last two question marks are nonsense. The last capturing group only considers small letters; according to your question you want case-insensitivity.

\d{1,2}?:\d\d(?)(am|pm)??
Comments