[英]How can I replace \ with / in Java?
I tried with following regex, but it didn't work. 我尝试使用以下正则表达式,但它没有用。
myString.replaceAll("\\", "/");
myString.replaceAll(“\\”,“/”);
Exception: 例外:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \\ ^ at java.util.regex.Pattern.error(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.util.regex.Pattern.(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.lang.String.replaceAll(Unknown Source)
java.util.regex.PatternSyntaxException:java.util.regex上java.util.regex.Pattern.compile(未知源)的java.util.regex.Pattern.error(未知源)索引1 \\ ^附近的意外内部错误.atat。(未知来源)java.lang.reatx.Pattern.compile(未知来源)java.lang.String.replaceAll(未知来源)
Your code should not even compile. 你的代码甚至不应该编译。
"\\"
escapes the "
so that the string continues. Writing String h = "\\"hello\\"";
makes the string h
contain "hello"
. "\\"
转义"
以便字符串继续。写入String h = "\\"hello\\"";
使字符串h
包含"hello"
。
If we change then change it to it to "\\\\"
(escaping the backslash) we run into another problem. 如果我们改变然后将其更改为
"\\\\"
(逃避反斜杠)我们遇到另一个问题。 The regular expression then tries to escape the next character. 然后正则表达式尝试转义下一个字符。 For example writing
"\\\\d+"
is a valid regular expression (matching digits). 例如,写
"\\\\d+"
是有效的正则表达式(匹配数字)。
In you case however you do not need regular expressions at all. 在你的情况下,你根本不需要正则表达式。 Just use the
replace(char, char)
method of the string, it replaces all characters. 只需使用字符串的
replace(char, char)
方法,它就会替换所有字符。
myString.replace('\\', '/');
By the way, if you are replacing paths, you should look at File.separator
to get the systems path separator character . 顺便说一句,如果要替换路径,则应该查看
File.separator
以获取系统路径分隔符 。
Sometimes you need 4 slashes, because backslash is an escape character for regex as well. 有时你需要4个斜杠,因为反斜杠也是正则表达式的转义字符。 Try
尝试
myString.replaceAll("\\\\", "/");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.