Splitting a Java String by the pipe symbol using split("|")

JavaRegexString

Java Problem Overview


The Java official documentation states:

The string "boo:and:foo", for example, yields the following results with these expressions Regex Result :

{ "boo", "and", "foo" }"

And that's the way I need it to work. However, if I run this:

public static void main(String[] args){
        String test = "A|B|C||D";
        
        String[] result = test.split("|");
        
        for(String s : result){
            System.out.println(">"+s+"<");
        }
    }

it prints:

><
>A<
>|<
>B<
>|<
>C<
>|<
>|<
>D<

Which is far from what I would expect:

>A<
>B<
>C<
><
>D<

Why is this happening?

Java Solutions


Solution 1 - Java

You need

test.split("\\|");

split uses regular expression and in regex | is a metacharacter representing the OR operator. You need to escape that character using \ (written in String as "\\" since \ is also a metacharacter in String literals and require another \ to escape it).

You can also use

test.split(Pattern.quote("|"));

and let Pattern.quote create the escaped version of the regex representing |.

Solution 2 - Java

Use proper escaping: string.split("\\|")

Or, in Java 5+, use the helper Pattern.quote() which has been created for exactly this purpose:

string.split(Pattern.quote("|"))

which works with arbitrary input strings. Very useful when you need to quote / escape user input.

Solution 3 - Java

Use this code:

public static void main(String[] args) {
    String test = "A|B|C||D";

    String[] result = test.split("\\|");

    for (String s : result) {
        System.out.println(">" + s + "<");
    }
}

Solution 4 - Java

You could also use the apache library and do this:

StringUtils.split(test, "|");

Solution 5 - Java

You can also use .split("[|]").

(I used this instead of .split("\\|"), which didn't work for me.)

Solution 6 - Java

test.split("\\|",999);

Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"

But test.split("\\|"); will return different length strings arrays for the same examples.

use reference: link

Solution 7 - Java

the split() method takes a regular expression as an argument

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbluehalluView Question on Stackoverflow
Solution 1 - JavajmjView Answer on Stackoverflow
Solution 2 - JavaAaron DigullaView Answer on Stackoverflow
Solution 3 - JavaberliandiView Answer on Stackoverflow
Solution 4 - JavaSimonView Answer on Stackoverflow
Solution 5 - JavaHomerView Answer on Stackoverflow
Solution 6 - JavaRyan AugustineView Answer on Stackoverflow
Solution 7 - JavaStormyView Answer on Stackoverflow