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?

Recommended Answers

All 3 Replies

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 :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.