• Post Reply Bookmark Topic Watch Topic
  • New Topic

String.replaceAll("\","/") proper syntax  RSS feed

 
g forte
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I was wondering what the proper syntax for the replaceAll method was if I wanted to replace all instances of \ with /

TIA!
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Reader,
I guess it will be this: replaceAll("\\", "/");

Backslash has a special meaning in Java such that "\n" means a new line and "\t" means a tab space.

Similarly, if you typed reaplceAll("\", "/") in this way, then the backslash is ignored and the character immediately following it (in this case ") is taken as a String literal.

Umm, I am not being able to explain it properly so I'll leave it at this. Hope somebody comes along with better explanatory skills.
 
g forte
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great That worked!

Thanks Shyam.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Backslash has a special meaning in Java strings and in regular expressions. To include a single '\' in a Java string, you have to "escape" it by doubling it:

String oneSlash = "\\";

But backslashes also have special meaning in regular expressions. To cancel the special meaning, you have to double it again, meaning the regular expression must have two backslashes. But to get a backslash into a String, you must double it. Therefore, the regular expression matching a single backslash is, in Java syntax

String oneSlashInRegex = "\\\\";

Four backslashes! Therefore you want

myString.replaceAll("\\\\", "/");
 
g forte
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually it compiled with no problem but when I run it I get this error:

Here is my code first:


Here is my error:

java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
 
g forte
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest that did it!!
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Reader,
Hmm.. I never knew that. Thanks for that.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!