Escape space with backslash in java

23,576

You could change

path = path.replaceAll(" ", "\\ ");

to escape the backslash

path = path.replaceAll(" ", "\\\\ ");

When I do that, I get (the requested)

/Users/TD/San\ Diego

Another option would be using String.replace like

path = path.replace(" ", "\\ ")

which outputs the same.

Share:
23,576
Admin
Author by

Admin

Updated on July 21, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to replace spaces from path string. I tried below but doesn't seems to be working :

    String path = "/Users/TD/San Diego";
    path=path.replaceAll(" ","\\ ");
    System.out.println(path);
    

    Goal is to convert

    "/Users/TD/San Diego" to "/Users/TD/San\ Diego"

    Any further space from string also needs to be replaced with "\ "