-2

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("\\", "//");
Fahad Murtaza
  • 256
  • 2
  • 9
  • 18

3 Answers3

2

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
Mena
  • 47,782
  • 11
  • 87
  • 106
  • sorry i have posted the opposite of the question. i have not edited it. please tell me the solution – Fahad Murtaza Apr 09 '14 at 15:28
  • @FahadMurtaza This is the solution. If the replace is backwards, I'm sure you can figure out how to switch which character is replaced. – Justin Apr 09 '14 at 15:34
1

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)

Community
  • 1
  • 1
ifloop
  • 8,079
  • 2
  • 26
  • 35
0

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

Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76