Java 字符串由字符组成。为了允许 Java 程序员将字符串作为“常量”和 Java 代码的一部分输入,该语言允许您将它们输入为用“””引号括起来的字符.....
String str = "this is a string";
有些字符很难输入到程序中,例如换行符或制表符。Java 引入了一种转义机制,允许程序员将这些字符输入到字符串中。转义机制是“\”反斜杠。
String str = "this contains a tab\t and newline\n";
问题是现在没有简单的方法来输入反斜杠,所以输入反斜杠必须自己转义:
String str = "this contains a backslash \\"
下一个问题是正则表达式是复杂的东西,它们还使用反斜杠\
作为转义字符。
Now in, for example, perl, the regular expression \.
would match the exact character '.' because in regular expressions the '.' is special, and needs to be escaped with a '\'. To capture that sequence \.
in a Java program (as a string constant in the program) we will need to escape the '\' as \\
and our Java equivalent regular expression is \\.
. Now, in perl, again, the regular expression to match the actual backslash character is \\
. Similarly, we need to escape both of these in Java in the actual code, and it is \\\\
.
所以,这里的意义在于windows中的文件分隔符是反斜杠\
。此单个字符存储在字段 File.separator 中。如果我们想从 Java 程序中输入相同的字符,我们必须将其转义为\\
,但是 '\' 已经存储在该字段中,因此我们不需要为 Java 程序重新转义它,但是我们确实需要为正则表达式转义它....
对于正则表达式,有两种方法可以对其进行转义。您可以选择在它之前添加一个反斜杠:
"\\" + File.separator
但这是一种不好的方法,因为它在 Unix 上不起作用(分隔符不需要转义。更糟糕的是做你所做的,即加倍文件分隔符:
File.separator+File.separator
The right way to do it is to correctly escape the replacement side of the regular expression with Matcher.quoteReplacement(...)
System.out.println(Test.class.getName().replaceAll("\\.",
Matcher.quoteReplacement(File.separator)) + ".class ")