Ok so I'm working on an assignment for my CS class.

One of the methods needs to check that a string is a valid input and the easiest way is to use the .matches method.

my method is

static boolean validateCourseId(String courseId)
    {
        boolean valid = courseId.matches("^CS [1234]\d\d\d$");
        return valid;
    }

I keep getting an error that says illegal escape character. I know it's talking about the\d, but I don't understand why it would give me that error?

I know I could just do [0123456789], but that's not the nice shorthand way

Can anyone help?

Since "\" is itself an escape character in strings, you have to escape them as well "\\".

Since "\" is itself an escape character in strings, you have to escape them as well "\\".

Yay that got it to work. Thank you so much! I appreciate your help!

It's not much shorter, but to specify exactly three digits you can use \d{3} instead of \d\d\d . Not much difference for just three, but 43 would be a different story :).

This question has already been answered. Start a new discussion instead.