简体   繁体   中英

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("\\", "//");

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM