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

前端 未结 4 552
傲寒
傲寒 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: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.

提交回复
热议问题