java使用split切割字符串的时候,注意转义字符

时间:2023-03-09 21:20:10
java使用split切割字符串的时候,注意转义字符

今天在做项目的时候发现一个奇怪的问题

 File file = new File("d:\\a.txt");
BufferedReader br = new BufferedReader(new FileReader(file)); String text = "";
while ((text = br.readLine()) != null) { String[] s = text.split("|");
for (int i = 0; i < s.length; i++) {
System.out.print("切割字符串" + s[i] + "\t");
}
System.out.println();
}
br.close();

运行的结果
java使用split切割字符串的时候,注意转义字符

发现每一个字符都给我切割了,后来在网上查到,当以  |  切割的时候一定要注意使用转义字符

 File file = new File("d:\\a.txt");
BufferedReader br = new BufferedReader(new FileReader(file)); String text = "";
while ((text = br.readLine()) != null) { String[] s = text.split("\\|");
for (int i = 0; i < s.length; i++) {
System.out.print("切割字符串" + s[i] + "\t");
}
System.out.println();
}
br.close();

搞定收工~