Java String Handling RegEx

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 regular expression and it needs to be escaped before split string by pipe.

How to split string by pipe in Java?

Suppose you have a CSV file separated by 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, you need to split the string by pipe.

Output

Expected output was an array with three elements 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 regular expression pattern for which we passed the pipe symbol. Pipe symbol is a metacharacter in regular expression and it means “OR”. So when we say split the string by “|”, it means that split the string by “empty string OR empty string”, this it returns all the characters of the source String along with empty strings.

If you want to split the string by literal pipe symbol (|), you need to escape it using “\\”. 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 quote method of Pattern class instead of escaping the pipe.

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

Output

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

 

Tags
Join 1000+ fellow learners! Enter your email address below: