1.符串中反斜杠
反斜杠(\)在JAVA中有特别的意义;它和紧跟着它的那个字符构成转义字符,如"\n"(表示换行)" \’ "(表示字符[ ’ ])等,所以在字符串中要表示反斜杠 \ 要用" \\ "来表示。例如这样定义一个字符串String s = "name\sex"是错误的,要这样定义String s = “name\\sex”
如下定义一个非法的字符串,会报错
String regx = "women\halou";
System.out.print(regx);
输出:
Error:(17, 30) java: 非法转义符
如下定义一个正确的字符串
String regx = "women\\halou";
System.out.print(regx);
输出:
women\halou
Process finished with exit code 0
2. 正则表达式中反斜杠
在正则表达式中的“\\”和后面紧跟着的那个字符构成一个转义字符,代表着特殊的意义;所以如果你要在正则表达式中表示一个反斜杠\,应当写成“\\\\”。
下面匹配A\
String regx = "\u0041\\\\";
Pattern p = Pattern.compile(regx);
Matcher m = p.matcher("A\\\\b");
while(m.find()){
System.out.println(m.group());
}
输出:
D:\ProgramFiles\eclipse\eclipse\JDK\bin\java.exe...
A\
Process finished with exit code 0
下面匹配电话号码
String regx = "\\d\\d\\d\\d-\\d\\d\\d\\d\\d\\d\\d";
Pattern p = Pattern.compile(regx);
Matcher m = p.matcher("小明的电话号码为:0563-4667722,小方的电话为:0555-7777777");
while(m.find()){
System.out.println(m.group());
}
输出:
0563-4667722
0555-7777777
Process finished with exit code 0