[英]ReplaceAll Method
我想在我的字符串中用這個“/”替換“\\”。 為此,我正在使用方法 replaceAll。 但它給了我錯誤。
String filePath = "D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg";
String my_new_str = filePath.replaceAll("\\", "//");
只需使用replace
。
方法replaceAll
需要一個正則表達式,你的將是格式錯誤的。
String filePath = "D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg";
System.out.println(filePath.replace("/", "\\"));
輸出
D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg
當您絕對想為此使用正則表達式時,請使用:
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg";
String my_new_str = filePath.replaceAll("\\\\", "/");
my_new_str
輸出將是:
D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg
只是一定要注意雙反斜杠\\\\
在源String
(您使用單一的人\\
你的問題。)
但梅納在他的回答中展示了一種更簡單、更易讀的方法來實現同樣的目標。 (只需采用斜杠和反斜杠)
你不能,因為字符'//'應該只輸入一個'/' 。
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\", "/");
上面可能會在執行過程中失敗給你一個PatternSyntaxException ,因為第一個 String 是一個正則表達式所以你使用這個,
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\\\", "/");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.