954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help with regular expression problem

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?

Forte1292
Newbie Poster
14 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

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

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 
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!

Forte1292
Newbie Poster
14 posts since Mar 2010
Reputation Points: 10
Solved Threads: 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 :).

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You