Yharoomanner
Yharoomanner

Reputation: 155

Java - String splits by every character

When I try to split a string with a delimiter "|", it seems to split every single character.

This is my line which is causing the problem:

String out = myString.split("|");

Upvotes: 12

Views: 15183

Answers (4)

Sunil Solanki
Sunil Solanki

Reputation: 3

This is how it worked for me!

 String tivoServiceCodes = "D1FAMN,DTV|SKYSP1,DTV|MOV01,VOD";
    String[] serviceCodes = tivoServiceCodes.split("\\|");
    for(String sc : serviceCodes){
        System.out.println(sc.toString());
    }

Upvotes: 0

Farsuer
Farsuer

Reputation: 306

In regex, | is a reserved character used for alternation. You need to escape it:

String out = string.split("\\|");

Note that we used two backslashes. This is because the first one escapes the second one in the Java string, so the string passed to the regex engine is \|.

Upvotes: 29

I think this was already answered in Java split string to array

In summary of the answers in the link above:

String[] array = values.split("\\|",-1);

This is because:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Upvotes: 1

yshavit
yshavit

Reputation: 43391

split takes a regular expression, in which | is a special character. You need to escape it with a backslash. But the backslash is a special character in Java strings, so you need to escape that, too.

myString.split("\\|")

Upvotes: 1

Related Questions