Split string with | separator in java

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 \ :).


The parameter to split method is a regex, as you can read here. Since | has a special meaning in regular expressions, you need to escape it. The code then looks like this (as others have shown already):

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

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

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

Tags:

Java

String

Split