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.
1 |
String strHeader = "empid|firstname|lastname"; |
In order to extract the header field labels, we need to split the string by pipe.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.javacodeexamples.stringexamples; import java.util.Arrays; public class StringSplitByPipeExample { public static void main(String[] args) { String strHeader = "empid|firstname|lastname"; String[] strFields = strHeader.split("|"); System.out.println( Arrays.toString(strFields) ); } } |
Output
1 |
[, e, m, p, i, d, |, f, i, r, s, t, n, a, m, e, |, l, a, s, t, n, a, m, e] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.javacodeexamples.stringexamples; import java.util.Arrays; public class StringSplitByPipeExample { public static void main(String[] args) { String strHeader = "empid|firstname|lastname"; String[] strFields = strHeader.split("\\|"); System.out.println( Arrays.toString(strFields) ); } } |
Output
1 |
[empid, firstname, lastname] |
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.
1 |
public static String quote(String pattern) |
The quote
method returns the literal pattern string for the specified pattern as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.javacodeexamples.stringexamples; import java.util.Arrays; import java.util.regex.Pattern; public class StringSplitByPipeExample { public static void main(String[] args) { String strHeader = "empid|firstname|lastname"; String[] strFields = strHeader.split( Pattern.quote("|") ); System.out.println( Arrays.toString(strFields) ); } } |
Output
1 |
[empid, firstname, lastname] |
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.