Reputation: 155
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
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
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
Reputation: 392
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 alimit
argument of zero. Trailing empty strings are therefore not included in the resulting array.
Upvotes: 1
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