Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String Split by "|"

I am trying to parse some data using Java which is separated by '|' sequence. Below is an example of the data.

String s = "111206|00:00:00|2|64104|58041"; String [] temp = s.split("|"); for(String p: temp) System.out.println(p); 

But instead of splitting at '|' it separates every character separately. Here is the output I get for the above code.

 1  1  1  2  0  6  |  0  0  :  0  0  :  0  0  |  2  |  6  4  1  0  4  |  5  8  0  4  1 

I found a turn around by replacing the '|' by ',' in the line, but the patch of code is going to run many times and I want to optimize it.

 String s = "111206|00:00:00|2|64104|58041";  s = s.replace('|', ','); 

I just want to know what the problem is with '|' ??

like image 294
Vijay Avatar asked May 01 '13 01:05

Vijay


People also ask

What is split () function in string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can we split by DOT in Java?

To split a string with dot, use the split() method in Java. str. split("[.]", 0);

What is split () in Java?

The split() method divides the string at the specified regex and returns an array of substrings.


1 Answers

You must use:

String [] temp = s.split("\\|"); 

This is because the split method takes a regular expression, and | is one of the special characters. It means 'or'. That means you are splitting by '' or '', which is just ''. Therefore it will split between every character.

You need two slashes because the first one is for escaping the actual \ in the string, since \ is Java's escape character in a string. Java understands the string like "\|", and the regex then understands it like "|".

like image 135
tckmn Avatar answered Sep 18 '22 06:09

tckmn