java中replaceAll方法的特殊问题

java中replaceAll方法的特殊问题,java,regex,string,Java,Regex,String,我的意见如下: Input: 6jVYY3Xnqt<>:"/\|?*GjznpnRQSb testInput = testInput.replaceAll("[<>:/\\\"|?*]", "-"); output: 6jVYY3Xnqt----\---GjznpnRQSb 输入:6jVYY3Xnqt:“/\ \?*GjznpnRQSb testInput=testInput.replaceAll(“[:/\ \ \”?*]”,“-”; 输出:6jVYY3Xnqt---

我的意见如下:

Input: 6jVYY3Xnqt<>:"/\|?*GjznpnRQSb
testInput = testInput.replaceAll("[<>:/\\\"|?*]", "-");
output: 6jVYY3Xnqt----\---GjznpnRQSb
输入:6jVYY3Xnqt:“/\ \?*GjznpnRQSb
testInput=testInput.replaceAll(“[:/\ \ \”?*]”,“-”;
输出:6jVYY3Xnqt-------GjznpnRQSb
但如果我这样做:

testInput = testInput.replaceAll("[<>:/\"|?*]", "-");
testInput = testInput.replace("\\", "-");
output: 6jVYY3Xnqt--------GjznpnRQSb
testInput=testInput.replaceAll(“[:/\”|?*]”,“-”;
testInput=testInput.replace(“\\”,“-”);
输出:6jVYY3Xnqt------GjznpnRQSb

这是java 7中的一个错误吗?为什么
replaceAll
不使用
\
字符?

您需要在正则表达式中双转义反斜杠,一次转义字符串文本,一次转义正则表达式:

testInput= testInput.replaceAll("[<>:/\\\\\"|?*]", "-");
//                                    ^^^^
//                                    Represents one backslash
testInput=testInput.replaceAll(“[:/”?*],“-”;
//                                    ^^^^
//表示一个反斜杠