Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Escape Sequence doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Escape Sequence doubt" Watch "Escape Sequence doubt" New topic
Author

Escape Sequence doubt

saloni jhanwar
Ranch Hand

Joined: Feb 09, 2012
Posts: 583

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


Tell the difficulties that i am difficult.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

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

Joined: Feb 09, 2012
Posts: 583

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

Joined: Feb 09, 2012
Posts: 583

thanks Matthew Brown, i got it.
Helen Ma
Ranch Hand

Joined: Nov 01, 2011
Posts: 451
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 \\

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Escape Sequence doubt
 
Similar Threads
Tokenizing
Tokenizing with scanner
Tokenizing with regex pattern. Little confused!
Tokenizing
Tokenizing with String.split()