Question

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("\\", "//");
Was it helpful?

Solution 2

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)

OTHER TIPS

Just use replace.

The method replaceAll takes a regular expression and yours would be malformed.

String filePath = "D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg";
System.out.println(filePath.replace("/", "\\"));

Output

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

You are unable because character '//' should be typed only single '/'.

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

Above may be fail during execution giving you a PatternSyntaxException, because the first String is a regular expression so you use this,

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

Check this Demo ideOne

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top