How to Split by Vertical Pipe Symbol "|" in Java


How can we split a string by the pipe symbol | in Java?

Given a string, we can use String::split to split the string around some regular expression.

However, note that the pipe symbol | is a special character. It is an OR operation.

Suppose we execute the following code:

String[] splitByPipe(String str) {
  return str.split("|");
}

Because String::split accepts a regular expression, passing | into split() will split on either "" or "", which evaluates to every character in the string.

We’ll want to escape this pipe symbol using a backslash \.

String[] splitByPipe(String str) {
  return str.split("\\|");
}

Note that we’ll need two backslashes because backslash is also a special character.

The first backslash escapes the second backslash in the string (i.e. Java sees the string as \|).

The second backslash escapes the pipe for the regular expression (i.e. the regex sees the string as |).

Read more on how to escape special, meta characters with backslashes in Java.