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. 8.7.1.8.7.1.1. Split with a limit less than zeroAny 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). 8.7.1.2. Split with a limit of zeroAn explicit limit of zero is the same as if there were no limit given, i.e., trailing empty elements are suppressed. 8.7.1.3. Split with a limit greater than zeroWith 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[0] is the family name . // NameInfo[1] is the given name . // NameInfo[2] is the middle name (or in my case, middle names) . // NameInfo[3] 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. |