Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace " \ " with " \\ " in java

I tried to break the string into arrays and replace \ with \\ , but couldn't do it, also I tried String.replaceAll something like this ("\","\\");.

I want to supply a path to JNI and it reads only in this way.

like image 712
David Prun Avatar asked Sep 23 '11 22:09

David Prun


2 Answers

Don't use String.replaceAll in this case - that's specified in terms of regular expressions, which means you'd need even more escaping. This should be fine:

String escaped = original.replace("\\", "\\\\");

Note that the backslashes are doubled due to being in Java string literals - so the actual strings involved here are "single backslash" and "double backslash" - not double and quadruple.

replace works on simple strings - no regexes involved.

like image 170
Jon Skeet Avatar answered Oct 15 '22 13:10

Jon Skeet


You could use replaceAll:

String escaped = original.replaceAll("\\\\", "\\\\\\\\");
like image 29
Bibin Mathew Avatar answered Oct 15 '22 12:10

Bibin Mathew