Search code examples
javaregexreplaceall

ReplaceAll Method


I want to replace "\" with this "/" in my string. I am using method replaceAll for this. But it is giving me error.

String filePath = "D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg";
String my_new_str = filePath.replaceAll("\\", "//");

Solution

  • When you absolutely want to use regex for this, use:

    String filePath   = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg";
    String my_new_str = filePath.replaceAll("\\\\", "/");
    

    Output of my_new_str would be:

    D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg
    

    Just be sure to notice the double backslashes \\ in the source String (you used single ones \ in your question.)


    But Mena showed in his answer a much simpler, more readable way to achive the same. (Just adopt the slashes and backslashes)