Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Escape Sequence doubt

 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It works fine with "\d" whereas with "\\d" why does it gives output like this ? while i have to use "c:\\scjp\\mytxt.txt" for IO operations.


Output : -

C:\SCJP\Chapter6\Tokenizing>java SplitMethod "as3ds65df6" "\d"
as
ds

df

C:\SCJP\Chapter6\Tokenizing>java SplitMethod "as3ds65df6" "\\d"
as3ds65df6

 
Matthew Brown
Bartender
Posts: 4566
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you wanting to split on the digits? In that case, the correct regular expression is \d. \\d means something else as a regular expression: it would look to split on a '\' character followed by a 'd'.

I'm guessing the source of your confusion is that you're thinking an extra \ is needed to escape the \. But that's when you're putting the regular expression into a Java string literal. When you're passing the regular expression in as a command-line argument that isn't necessary.

So with the code you've got, you call it with the line java SplitMethod "as3ds65df6" "\d". But using a string literal, the following code would give the same result:
 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From book k&B 504 page

So, what if you need to search for periods (.) in your source data? If you just put a period in the regex expression, you get the "any character" behavior. So, what if you try \. ? Now the Java compiler thinks you're trying to create an escape sequence that doesn't exist. The correct syntax is




but if i do so then it doesn't work. for me it is correct "\." not "\\."for dot.
 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Matthew Brown, i got it.
 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Saloni,
Maybe you can try this:


to see if it works for a dot sign in a regex.

According to the book, \\. represents a dot. In the Java code, \\ represents a \. Therefore, \\\\ represents \\

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic