Examples of the split method

Let's look at the following code listing, which splits the subject string on each occurrence of a hyphen:

package example.regex; import java.util.*; class StringSplit {   public static void main (String[] args)   {     final String input = "green-red-blue-yellow";     Arrays.stream(input.split("-"))    .forEach(System.out::println);   } } 

This will generate the following output:

"green" "red" "blue" "yellow" 

Now, let's change our code to the following by splitting on each occurrence of the letter e:

Arrays.stream(input.split("e")) .forEach(System.out::println); 

The preceding code will generate the following output:

"gr" "" "n-r" "d-blu" "-y" "llow" 

We got one empty result because we split on each e and there are ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.