转义字符'\'的作用是,和其后面的一个或多个字符一起,表示一个特殊字符,如"\n"这两个字符来表示一个换行符。
java
System.out.println("\n".length()); // 1
1
Java语言有以下转义字符:
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a formfeed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
其他语言里也有类似的转义字符。
另外java中还有一类转义字符,和前面列的转义字符不同,这些转义字符是预编译的(在编译之前已经被替换为正常字符了)。
这样的转义字符有两类:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
其中
\u和其后面的4个字符(有效的16进制数字[0-9a-fA-F])表示一个16进制的unicode值;
\和其后面的1-3个字符(范围为{0-377}的8进制有效数字)表示一个8进制的unicode值。
我们看几个例子:
public static void main(String[] args) throws Exception {
System.out.println("\u0031"); // 1
System.out.println("\u4E2D"); // 中
System.out.println("\100"); // @
System.out.println("\376"); // þ
System.out.println("\0771"); // ?1
System.out.println("\779"); // ?9
System.out.println("\12A"); // 相当于打印"\nA"
}
1
2
3
4
5
6
7
8
9
输出结果:
1
中
@
þ
?1
?9
A
————————————————
版权声明:本文为CSDN博主「xuejianbest」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xuejianbest/article/details/100739503
java中需要转义的字符
在Java中,不管是String.split(),还是正则表达式,有一些特殊字符需要转义,
这些字符是
( [ { / ^ - $ ¦ } ] ) ? * + .
转义方法为字符前面加上"\\",这样在split、replaceAll时就不会报错了;
不过要注意,String.contains()方法不需要转义。