JavaDevNotes.com

Java String Split Pipe Examples

Sometimes it is not appropriate to split a String using whitespaces. For example, when items are expected to be phrases. Usually, it is more useful to select a special character to split a String. Here is an example on how to Split a Java String using pipe ( | ) as delimiter.

Incorrect Split using pipe

We usually don't want to pass the pipe character directly to the String Split's method. Say for example we wish to split the String "A | B | C" and get the individual characters. If we use this code below:

public class TestConsole {
   public static void main(String[] args) {
      String sampleString = "A |  B |   C";
      String[] items = sampleString.split("|");
      int itemIndex = 1;
      for (String item : items) {
         System.out.println(itemIndex + ". " + item);
         itemIndex++;
      }
   }
}

The output will be like this:

1. 
2. A
3.  
4. |
5.  
6.  
7. B
8.  
9. |
10.  
11.  
12.  
13. C

This is unexpected as we wish to only get three items. The reason for this is because the character pipe has special meaning to regular expressions.

Proper Split using pipe

The right approach is to escape the pipe character with \. Here is an example:

public class TestConsole {
   public static void main(String[] args) {
      String sampleString = "A |  B |   C";
      String[] items = sampleString.split("\\|");
      int itemIndex = 1;
      for (String item : items) {
         System.out.println(itemIndex + ". " + item);
         itemIndex++;
      }
   }
}
And here is the sample output:
1. A 
2.   B 
3.    C

Notice that I placed spaces on sampleString ("A | B | C") on purpose. Although we got the correct three items, each was not trimmed.

Split using pipe with trim

Here is a better approach. Check the code below:
public class TestConsole {
   public static void main(String[] args) {
      String sampleString = "A |  B |   C";
      String[] items = sampleString.split("\\s*\\|\\s*");
      int itemIndex = 1;
      for (String item : items) {
         System.out.println(itemIndex + ". " + item);
         itemIndex++;
      }
   }
}
As you could see, I modified the regular expression \|. I added a sequence of zero or more white space (\s*) both on the left and on the right. The result is that each token found now is trimmed at both sides.
1. A
2. B
3. C

String Tutorials And Examples