在Java中用’\\’替换单个’\’

如何用'\\'替换单个'\' '\\' ? 当我运行replaceAll()然后我收到此错误消息。

 Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \ ^ at java.util.regex.Pattern.error(Pattern.java:1713) at java.util.regex.Pattern.compile(Pattern.java:1466) at java.util.regex.Pattern.(Pattern.java:1133) at java.util.regex.Pattern.compile(Pattern.java:823) at java.lang.String.replaceAll(String.java:2190) at NewClass.main(NewClass.java:13) Java Result: 1 

我的代码:

 public class NewClass { public static void main(String[] args) { String str = "C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes"; str = str.replaceAll("\\", "\\\\"); System.out.println(str); } } 

String.replaceAll(String,String)是正则表达式。
String.replace(String,String)将执行您想要的操作。

下列…

 String str = "C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes"; System.out.println(str); str = str.replace("\\", "\\\\"); System.out.println(str); 

生产…

C:\ Documents and Settings \ HUSAIN \ My Documents \ My Palettes
C:\\ Documents and Settings \\ HUSAIN \\ My Documents \\ My Palettes

\也是正则表达式中的特殊字符。 这就是为什么你应该做这样的事情:

  str = str.replaceAll("\\\\", "\\\\\\\\"); 

你必须首先对字符串进行scape,然后将其用于正则表达式,每个斜杠都是\\\\

在字符串文字中, \必须使用另一个\进行转义。 在一个reges中,一个\也必须被另一个\\逃脱。 所以,你必须每四次逃脱: \\\\

另一种方法是使用Pattern.quote("\\") (对于正则表达式)和Matcher.quoteReplacement("\\\\")作为替换字符串。

您可以使用Pattern.quote使您更容易转义值,例如:

 str = str.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\")); 

或者,您可以使用String.replace

 str = str.replace("\\", "\\\\"); 

请参阅: Pattern.quote , String.replace和Matcher.quoteReplacement

filePath = filePath.replaceAll(Matcher.quoteReplacement(“\”),Matcher.quoteReplacement(“\\”));

这个工作完美。 filePath = C:\ abc \