gstackoverflow gstackoverflow - 4 months ago 8
Java Question

Check that String is alphanumeric with length 1 to 5

I have wrote the following test code snippet:

"123".matches("\\[a-zA-Z0-9]{1,5}");


However, it returns
false
.

Why and how to fix this?

Answer

You're escaping the first square bracket with the \\, which means the expression between the square brackets isn't treated as a character class. Remove the escaping and you should be OK:

"123".matches("[a-zA-Z0-9]{1,5}"
// Here -------^