File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "When "\ Watch "When "\ New topic
Author

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

Emanuele Ghe
Ranch Hand

Joined: Feb 04, 2009
Posts: 111
Hi,
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
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

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


SCJP6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When "\'something'" or "\\'something'" will not compile
 
Similar Threads
Keywords ?
null is java keywork or not?.
doubt in constructors?
java
Operator self test question and Flow Control doubt.