File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes When Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "When "\ Watch "When "\ New topic

When "\'something'" or "\\'something'" will not compile

Emanuele Ghe
Ranch Hand

Joined: Feb 04, 2009
Posts: 111
I am quite confused on when to use '\' ,'\\' or even '\\\'.

I triple checked on K&B but I still fail 99% of questions regarding compilation of regex (questions about the Scanner class for example).

If someone has time, could try to clarify me these concepts?

From what I understood:

Java has reserved escape sequences :
\n = new line
\b = backslash
\t = tab

al the reserved escape sequence use only 1 '\', so trying to compile '\d' will give a compilation error.

Apart from this all the rest is completely unclear to me.

Thanks all.

SCJP6 with score 90%. I am conscious of my ignorance and ready to learn from everyone.
Ankit Garg

Joined: Aug 03, 2008
Posts: 9462

Well as you already know java uses \ for escape sequences. If you want to use \ in a String when the escape sequence is not legal, you use \\ instead of \. So in regex when you want to use \d, you'll have to escape \ so you'll write \\d. By doing this you'll pass the compilation and the regex engine will process it as \d...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
One notable exception to the rule of using \\ in the regex pattern is if you pass the regex pattern as a command line argument. If you do so, you simply use \ and not \\. I learnt this the hard way. Here is my made up example code:

Here is how you could run the code after compilation. If you see below, I am just using \ and not \\ and it still works. But this is the only exception to the rule i.e. if you use the regex from the command line. If you hard code the regex inside the code itself, then you need to use \\.
java Test "\w+"
java Test "\d"

But apparently iit also works if you use \\ instead of \ like shown below:
java Test "\\w+"
java Test "\\d"

Trying writing your own code and experimenting with it! Good luck.

Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
But, if we want to match a \ (backslash):

I agree. Here's the link:
subject: When "\'something'" or "\\'something'" will not compile
It's not a secret anymore!