Split string with | separator in java

Solution 1:

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

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

Solution 2:

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

Solution 3:

Escape the pipe. It works.

String.split("\\|");

The pipe is a special character in regex meaning OR

Solution 4:

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("\\|");

Solution 5:

It won't work this way, because you have to escape the Pipe | first. The following sample code, found at (http://www.rgagnon.com/javadetails/java-0438.html) shows an example.

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To";
    // bad
    System.out.println(java.util.Arrays.toString(
        testString.split("|")
    ));
    // output : [, R, e, a, l, |, H, o, w, |, T, o]

    // good
    System.out.println(java.util.Arrays.toString(
      testString.split("\\|")
    ));
    // output : [Real, How, To]
  }
}