String manyAnimals = "ant , bat, cat, dog" ; String[] pieces = manyAnimals.split( " *, *");
The array:
String pieces = {"ant", "bat", "cat", "dog"};
The RE is the same as before, but the items that are split into the array are different.
It is possible for two delimiters to occur with nothing between them. For example
String manyAnimals = "ant , , cat, dog" ; String[] pieces = manyAnimals.split( " *, *");
produces the array
String[] pieces = {"ant", "", "cat", "dog"};
The RE matches two substrings between ant and cat,
leaving no unmatched characters, so the
item that goes into the array is a reference to an empty string.
(Note that this is a String
object that contains
no characters, not the value null
.)
Also note that the white space at the beginning and end of a string may be included in an item the string has been split into. The following fragment
String manyPets = " ant , bat , cat " ; String[] pieces = manyAnimals.split( " *, *");
creates the array
String[] pieces = {" ant" , "bat", "cat "};
What array is produced by the following fragment:
String manyNumbers = "24 , 34; 987 007" ; String[] pieces = manyNumbers.split( " *[;, ]? *" );