jasondlee jasondlee - 3 years ago 100
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:


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.assertEquals("12:34AM", matcher.group());

Anyone have any idea why?

Answer Source

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


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.

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