我无法弄清楚为什么下面的代码没有按预期运行
"Hello/You/There".replaceAll("/", "\\/");
Run Code Online (Sandbox Code Playgroud)
Hello\/You\/ThereHello/You/There我需要向前逃避斜线吗?我不这么认为,但我也违背了我的意愿尝试了以下......没有用
"Hello/You/There".replaceAll("\\/", "\\/");
Run Code Online (Sandbox Code Playgroud)
最后,我意识到我不需要正则表达式,我只能使用以下内容,它不会创建正则表达式
"Hello/You/There".replace("/", "\\/");
Run Code Online (Sandbox Code Playgroud)
但是,我仍然想知道为什么我的第一个例子不起作用.
rua*_*akh 77
问题实际上是你需要在替换字符串中双重转义反斜杠.你看,"\\/"(因为我确定你知道)意味着替换字符串是\/,并且(因为你可能不知道)替换字符串\/实际上只是插入/,因为Java很奇怪,并且\在替换字符串中给出了特殊含义.(据说这\$将是一个字面上的美元符号,但我认为真正的原因是他们想要与人混淆.其他语言不这样做.)所以你必须写:
"Hello/You/There".replaceAll("/", "\\\\/");
Run Code Online (Sandbox Code Playgroud)
要么:
"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));
Run Code Online (Sandbox Code Playgroud)
(使用java.util.regex.Matcher.quoteReplacement(String).)