11

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("|");
Yharoomanner
  • 145
  • 1
  • 1
  • 5

4 Answers4

27

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

Sam
  • 20,096
  • 2
  • 45
  • 71
Farsuer
  • 286
  • 3
  • 3
  • 2
    Oh thanks! I thought one would escape it with one backslash but Android Studio told me it was an illegal escape character so I assumed it didn't need escaping. Thanks! – Yharoomanner Oct 04 '14 at 11:50
  • 4
    To clarify, it's not that the `|` character means an empty string. It means "or." It's just that this means that the regex in the question translates to "an empty string or an empty string." – yshavit Oct 04 '14 at 12:09
  • @Yharoomanner Note that the double backslash represents a backslash character in the input string. This is then passed to the regex parser as the string "\|" which represents a vertical bar character. – Code-Apprentice Oct 05 '14 at 03:36
1

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.

Community
  • 1
  • 1
1

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("\\|")
yshavit
  • 42,327
  • 7
  • 87
  • 124
0

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());
    }