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

69,242

Solution 1

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.

Solution 2

You could use replaceAll:

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

Solution 3

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

That's not right. You only need double backslashes in literal strings that you declare in a programming language. You never have to do this substitution at runtime. You need to rethink why you're doing this.

Share:
69,242
David Prun
Author by

David Prun

Updated on August 17, 2020

Comments

  • David Prun
    David Prun almost 4 years

    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.

  • James andresakis
    James andresakis over 10 years
    This adds four slashes like this \\\\ for me
  • Jon Skeet
    Jon Skeet over 10 years
    @Jamesandresakis: It's hard to tell what you're doing wrong with so little information. My guess is that you're looking at the string in a debugger, where it may be escaping it for you.