简体   繁体   English

全部替换方法

[英]ReplaceAll Method

I want to replace "\\" with this "/" in my string.我想在我的字符串中用这个“/”替换“\\”。 I am using method replaceAll for this.为此,我正在使用方法 replaceAll。 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 .只需使用replace

The method replaceAll takes a regular expression and yours would be malformed.方法replaceAll需要一个正则表达式,你的将是格式错误的。

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: my_new_str输出将是:

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.)只是一定要注意反斜杠\\\\在源String (您使用单一的人\\你的问题。)


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,上面可能会在执行过程中失败给你一个PatternSyntaxException ,因为第一个 String 是一个正则表达式所以你使用这个,

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

Check this Demo ideOne检查这个演示ideOne

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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