0

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?

2
Contributors
3
Replies
6
Views
5 Years
Discussion Span
Last Post by Ezzaral
Featured Replies
1

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

0

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!

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.