如何替换“\”与“/”在java中?
我有一个像 s = "abc\def" 这样的字符串,我想用 "/" 替换 "" 并使字符串像 "abc/def/" 一样。
我尝试了 replaceAll("\\","/")
但编译器给出了字符串错误
错误:非法转义字符 字符串 s="abc\def";
I have a string like s = "abc\def" and I want to replace "" with "/" and makes the string like "abc/def/".
I tried replaceAll("\\","/")
but the compiler is giving error for string
error: illegal escape character
String s="abc\def";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是 Java 使用
\
作为字符串转义字符,同时也作为正则表达式转义字符,并且replaceAll
执行正则表达式搜索。因此,您需要双重转义反斜杠(一次使其成为字符串中的文字\
,一次使其成为正则表达式中的文字字符):或者,这里实际上不需要正则表达式,因此以下方法也有效:
或者,实际上,使用单字符替换版本:
The issue is that Java uses
\
as the string escape character, but also as the regex escape character, andreplaceAll
performs a regex search. So you need to doubly escape the backslash (once to make it a literal\
in the string, and once to make it a literal character in the regular expression):Alternatively, you don’t actually need regular expressions here, so the following works as well:
Or, indeed, using the single-char replacement version: