Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Emanuele Ghe
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Larry Olson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But, if we want to match a \ (backslash):
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic