Skip to content

Java split String by Pipe Example

Java split String by pipe example shows how to split String by pipe in Java. Pipe (|) has a special meaning in the regular expression and it needs to be escaped before splitting the string by pipe.

How to split string by pipe in Java?

Suppose you have a CSV file separated by the pipe (|) symbol and you want to parse the records. The header record of the CSV file looks like below.

In order to extract the header field labels, we need to split the string by pipe.

Output

The expected output was an array with three elements namely empid, firstname and last name in that order. We got all the characters of the original string instead.

What happened here is that the split method takes a parameter as a regular expression pattern for which we passed the pipe symbol. The Pipe symbol is a metacharacter in the regular expressions and it means “OR”. So when we say split the string by “|”, it means that split the string by “empty string OR empty string”. That is why it returns all the characters of the source string along with the empty strings.

If you want to split the string by literal pipe symbol (|), you need to escape it using the “\\”. So, the regular expression pattern should be like “\\|” as given below.

Output

This output is what we had expected to get. You can also use the quote method of the Pattern class instead of escaping the pipe character.

The quote method returns the literal pattern string for the specified pattern as given below.

Output

This example is a part of the Java String tutorial and Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.