| 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: 3786
|
|
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 \\
|
 |
 |
|
|
subject: Escape Sequence doubt
|
|
|