How to replace “ \ ” with “ \\ ” in java

前端 未结 4 538
傲寒
傲寒 2020-11-29 10:35

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

相关标签:
4条回答
  • 2020-11-29 10:46

    You could use replaceAll:

    String escaped = original.replaceAll("\\\\", "\\\\\\\\");
    
    0 讨论(0)
  • 2020-11-29 10:52

    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.

    0 讨论(0)
  • 2020-11-29 10:53

    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.

    0 讨论(0)
  • 2020-11-29 10:59

    It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\" in a regex expression.

    here is the link where i found this information: https://www.rgagnon.com/javadetails/java-0476.html

    I had to convert '\' to '\\'. I found somewhere that we can use:

    filepathtext = filepathtext.replace("\\","\\\\"); 
    

    and it works. Given below is the image of how I implemented it.

    https://i.stack.imgur.com/LVjk6.png

    0 讨论(0)
提交回复
热议问题