Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange string split behaviour

I'm requesting data from my server and receive a string in the form of 2|bit.ly|1||1| and | should be the seperator.

I though the following piece of code should do the work

BufferedReader br = null;
...
br = new BufferedReader(new InputStreamReader(inputStream));
...

String line;
String[] columns;
ContentValues values;

while((line = br.readLine())!=null) {
    columns = line.split("|");
    ...
}

but after the line.split("|"); the colums contains 15 elements instead of expected 6. Taking a closer look at it's content reveals that each character in the string was stored in one array element.

Anyone having an idea, what's wrong with it? The code coming from server isn't encoded in any way in in the example I use only ASCII characters appear.

like image 667
Tseng Avatar asked Mar 04 '26 07:03

Tseng


1 Answers

String.split takes a regular expression as the split string, and the '|' character means OR in regex land. You need to escape that character, e.g. line.split("\\|");

Note the double backslash: You need to escape the backslash for the Java compiler so that the regex engine gets a literal backslash followed by a '|', which is then interpreted by the engine as a literal '|'.

like image 182
Cameron Skinner Avatar answered Mar 05 '26 21:03

Cameron Skinner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!