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?

4
  • 2
    The first line itself doesn't compile! Commented Jan 30, 2019 at 10:07
  • 2
    Perhaps you need to define strToReplace as "D:\\Work\\Project\\Data"; Commented Jan 30, 2019 at 10:08
  • I edited the question. The string contains value that I read from a property file. Commented Jan 30, 2019 at 10:15
  • Did you tried strToReplace.replace("\\","\\\\") ? Commented Jan 30, 2019 at 12:29

1 Answer 1

2

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

try following:

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

See following link

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.