str.split(""),什么时候加\\
转义?
在遇到
.$|()[{^?*+\\
(12个)需要加\\
java源代码
例子
(
和)
public class SplitTest {
public static void main(String[] args) {
System.out.println("测试(:");
String c = "1(2(3(4(5";
for (String s : c.split("\\(")){
System.out.print(s + " ");
}
System.out.println("\n测试):");
String c2 = "1)2)3)4)5";
for (String s : c2.split("\\)")){
System.out.print(s + " ");
}
}
}
运行结果:
\\
public class SplitTest {
public static void main(String[] args) {
String c = "1\\2\\3\\4\\5";
for (String s : c.split("\\\\")){
System.out.print(s + " ");
}
}
}
运行结果:
[
(注意:]
不需要转义)
public class SplitTest {
public static void main(String[] args) {
System.out.println("测试[:");
String c = "1[2[3[4[5";
for (String s : c.split("\\[")){
System.out.print(s + " ");
}
System.out.println("\n测试]:");
String c2 = "1]2]3]4]5";
for (String s : c2.split("]")){
System.out.print(s + " ");
}
}
}
运行结果:
{
(注意:}
不需要转义)
public class SplitTest {
public static void main(String[] args) {
//.$|()[{^?*+\
System.out.println("测试{:");
String c = "1{2{3{4{5";
for (String s : c.split("\\{")){
System.out.print(s + " ");
}
System.out.println("\n测试}:");
String c2 = "1}2}3}4}5";
for (String s : c2.split("}")){
System.out.print(s + " ");
}
}
}
运行结果:
str.replaceAll()同str.split()