1

I am trying to replace all \ characters to \\ by java. This may be silly question, but I have tried many things for it. My piece of attempt is below :

String strToReplace = oldString;

strToReplace = strToReplace.replaceAll("\\","\\\\");

The oldString contains "D:\Work\Project\Data". That I read from a property file. Above is giving me error :

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
 ^
    at java.util.regex.Pattern.error(Pattern.java:1955)
    at java.util.regex.Pattern.compile(Pattern.java:1702)
    at java.util.regex.Pattern.<init>(Pattern.java:1351)

Any other approach to do this?

Arnab Dhar
  • 239
  • 2
  • 15

1 Answers1

2

replaceAll interprets your argument as a RegEx. You need to double escape it.

try following:

string.replaceAll("\\\\", "\\\\\\\\");

See following link

student18
  • 538
  • 8
  • 26