Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with | separator in java

Tags:

java

string

split

I have a string that's like this: 1|"value"|;

I want to split that string and have chosen | as the separator.

My code looks like this:

String[] separated = line.split("|"); 

What I get is an array that contains all characters as one entry:

separated[0] = "" separated[1] = "1" separated[2] = "|" separated[3] = """ separated[4] = "v" separated[5] = "a" ... 

Does anyone know why?
Can't I split an string with |?

like image 254
Prexx Avatar asked Jun 10 '11 11:06

Prexx


People also ask

Can we split string with in Java?

You can use the split() method of java. lang. String class to split a string based on the dot. Unlike comma, colon, or whitespace, a dot is not a common delimiter to join String, and that's why beginner often struggles to split a String by dot.

How do you separate a string from a delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.

What is split () in Java?

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


2 Answers

| is treated as an OR in RegEx. So you need to escape it:

String[] separated = line.split("\\|"); 
like image 175
Talha Ahmed Khan Avatar answered Oct 21 '22 21:10

Talha Ahmed Khan


You have to escape the | because it has a special meaning in a regex. Have a look at the split(..) method.

String[] sep = line.split("\\|"); 

The second \ is used to escape the | and the first \ is used to escape the second \ :).

like image 43
Kevin Avatar answered Oct 21 '22 21:10

Kevin