8.7. Pattern's split Method, with Two Arguments
The limit argument takes on different meanings depending on whether it's less than zero, zero, or greater than zero.
184.108.40.206. Split with a limit less than zero
Any limit less than zero means to keep trailing empty elements in the array. Thus,
String result = Pattern.compile(":").split(":xx:", -1 );
returns an array of three strings (an empty string, ' xx ', and another empty string).
220.127.116.11. Split with a limit of zero
An explicit limit of zero is the same as if there were no limit given, i.e., trailing empty elements are suppressed.
18.104.22.168. Split with a limit greater than zero
With a limit greater than zero, split returns an array of, at most, limit elements. This means that the regex is applied at most limit - 1 times. (A limit of three, for example, requests three strings separated by two matches.)
After having matched limit - 1 times, checking stops and the remainder of the string (after the final match) is returned as the limit th and final string in the array.
For example, if you have a string with:
and want to isolate only the three name components , you'd split the string into four parts (the three name components, and one final "everything else" string):
String NameInfo = Pattern.compile(",").split(Text, 4 ); // NameInfo is the family name . // NameInfo is the given name . // NameInfo is the middle name (or in my case, middle names) . // NameInfo is everything else, which we don't need, so we'll just ignore it .
The reason to limit split in this way is enhanced efficiency why bother going through the work of finding the rest of the matches, creating new strings, making a larger array, etc., when the results of that work won't be used? Supplying a limit allows only the required work to be done.