1

I'm trying to write a regex for military time (0000-2359), but it lets through any hour up to 29. Why doesn't the expression throw the error for 24XX+?

    while(true)
    {
        try
        {       
            sInput = input.nextLine();

            // If the input is a properly formatted time break the loop
            // otherwise throw invalidTimeFormatException
            if(Pattern.matches("[0-2](?:(?=2)[0-3]|[0-9])[0-5][0-9]", sInput))
            {
                // This will only happen if the time is properly formatted
                // thanks to the regular expression above.
                break;
            }

            throw invalidTimeFormatException;
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }           
    }

2 Answers 2

7

I know that this was already answered and accepted, but I'd suggest using a more simple and explicit regex instead of using lookbehinds:

([0-1][0-9]|2[0-3])[0-5][0-9]

It's shorter, supported in every regex engine, and (to me at least) much clearer.

Sign up to request clarification or add additional context in comments.

Comments

2

You want a look-behind (?<=2) rather than look-ahead (?=2).

As it is, it's matching "first character 0, 1, or 2; next character, if it's a 2 then 0-3, otherwise 0-9; etc."

Edit: Actually, you'll need a negative look-behind (?<!2) to ensure the previous character is not 2 to match [0-9], and it needs to not be a non-capturing group:

[0-2]((?<=2)[0-3]|(?<!2)[0-9])[0-5][0-9]
                  \____/
                     |
add negative look-behind here

4 Comments

Doing this still gives the same problem.
Can't type this morning. Try it now.
Works! Thank you. Just one question, why ?<=2 and not ?<2?
I don't know. That's just the way they did it, I guess. It may have been for a very good reason, or for none at all. In some flavors (e.g. Ruby, and apparently Java 7) ?< by itself symbolizes the start of a named group (and so needs to be differentiated), but that was probably created afterwards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.