Issue with string split using pipe | in Java

I ran into an issue trying to use the Java String split method using a pipe (|) character. When I checked the array returned from the split method, it contained every character from the string I was trying to split, including the pipe delimiters.
Turns out I was making quite a noobish mistake. A quick glance at the javadocs for java.lang.String.Split() reveals the method signature is: String[] split(String regex)  

So passing a regex of “|” with no characters to match against results in everything within the string being matched and returned, hence the unexpected results.
Escaping the pipe character fixes the problem:

String stringToSplit = "1|2|3|4|5";
String[] splitString = stringToSplit.split("\\|");

for(String string : splitString) {


Anonymous said...

This actually helped me - Thanks for saving me the hassle :)