213

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?

1

7 Answers 7

457

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

Sign up to request clarification or add additional context in comments.

2 Comments

It is, split() method takes regex and | is special character for reg ex
you are my second choice as a moderator on stack overflow. All the best.
43

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.

1 Comment

Not shure when the transition was made, but in Java 8, one would use Pattern.quote().
6

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

1 Comment

This solution is already pointed by accepted answer. No need to repeat it.
3

You could also use the apache library and do this:

StringUtils.split(test, "|");

Comments

3

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

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

3 Comments

Both versions should work fine. If one doesn't it suggest problem is somewhere else.
@Pshemo This does however add an interesting flavor, that some reserved symbols does not have to be escaped if put inside brackets.
I also tried several alternative but for me on Java 25 only the "[|]" is working - thanks
1
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

Comments

-2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.