The Split function in Java is used to segment a string by a specified character (string) or regular, and the result is returned as an array of strings;
For example:
[Java] view plain copy String str= "1234@ABC"; String[] A = Str.split ("@"); SYSTEM.OUT.PRINTLN ("Processing results:" +a[0]+ "," +a[1]); Output is: Processing results: 1234,ABC for the split character (string), is usually common, ordinary, no problem;
However, for certain special characters, if the character (string) is just a part of the regular, you need to escape to use it.
These characters have |, +, *, ^, $,/, |, [,], (,),-,., etc, because they are part of the regular expression, so if you want to use the character itself, these characters need to be escaped to represent itself;
For example:
Want to use | Vertical bar to split a character, because | itself is a part of the regular expression, so you need to escape, because the escape using \, and this \ is also a regular expression of the character, so you have to use a \, so need two \.
[Java] view plain copy String str= "5678| XYZ "; String[] B = Str.split ("\\|"); Note that there are two \ n, not one \ System.out.println ("Processing results:" +b[0]+ "," +b[1]); The output is: processing results: 5678,XYZ
Take another look: [Java] view plain copy String str= "5678| XYZ "; String[] B = Str.split ("|"); Note Direct Use |, which is part of a regular expression, String x= "processing result:"; for (int i=0;i<b.length;i++) {x=x+b[i]+ ","; } System.out.println (x); Output is: processing result: 5,6,7,8,|,x,y,z, possibly we artificial subjective feeling is with | To split the hope to get 5678 and XYZ, because with special characters, the actual result is to get unexpected results;
So when you specify a split character (string), it is best not to include the character used for the regular expression itself, such as the red character above;