Java Tips & Tricks: Splitting a String on the Pipe “|” Delimeter

Recently I came across the issue in java where the split command I was executing was returning an array split on every character and not the | character as I had specified.

    String[] subStrings  = myString.split( "|" );

The reason for this functionality is that the | character represent a character delimeter. To split the string only on the | character we need to escape it. However do to the nature of the split method we need to escape twice so that the final regex string is an escaped |. This means me need the following to split on the Pipe | delimeter.

    String[] subStrings = myString.split( "\|" );

If you wanted to split on a double pipe then you would use the following:

    String[] substrings = myString.split( "\|\|" );
// Java // Tips & Tricks //

Comments & Questions

Add Your Comment