0

I have the code

private String regexHHMM = "^([0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$";

The code does not compile with the error "Unclosed Character class"

This must be something very basic, is there any particular escaping I should be using, also I am mainly interested on WHY it cannot be accepted by the java compiler.

UPDATE: I have tried

Pattern.quote("^([0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$"); 

And now it compiles, but the regex does not match the HH:MM format now...

1
  • Pattern.quote is for escaping all special character in the String, so that when it is compiled, the regex will match the characters in the original String literally. Commented Nov 26, 2014 at 5:08

1 Answer 1

4

You need to remove the initial open square bracket inside of your pattern.

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

Should be:

^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
Sign up to request clarification or add additional context in comments.

5 Comments

Good one, and I guess the reason it does not compile is because the java compiler parses every string?
@Gary: The character class can be nested arbitrarily deep in Java. It's called character class union.
@JuanAntonioGomezMoriano Are you sure it "does not compile"? Your declaration of regexHHMM is just a String variable initialized with a string literal. As far as I know, it isn't parsed as a regex until runtime when you call Pattern.compile or some other methods. What exactly is the "compiler"'s behavior?
@ajb: The regex is compiled at run time by Pattern class (implicitly via some method in String class or explicitly), and the OP's regex return a PatternSyntaxException.
@nhahtdh Right, "at run time" ... but OP is saying it's the compiler doing it, and asking if the "java compiler parses every string"...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.