bluehallu
bluehallu

Reputation: 10295

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

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?

Upvotes: 212

Views: 273975

Answers (7)

Aaron Digulla
Aaron Digulla

Reputation: 328860

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.

Upvotes: 43

Ryan Augustine
Ryan Augustine

Reputation: 1542

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

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240996

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 |.

Upvotes: 456

Homer
Homer

Reputation: 37

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

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

Upvotes: 2

berliandi
berliandi

Reputation: 71

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 + "<");
    }
}

Upvotes: 6

Simon
Simon

Reputation: 19948

You could also use the apache library and do this:

StringUtils.split(test, "|");

Upvotes: 3

Stormy
Stormy

Reputation: 641

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

Upvotes: -2

Related Questions