Section 8.7. Pattern s split Method, with Two Arguments

8.7. Pattern's split Method, with Two Arguments

String[] split( CharSequence text , int limit )

This version of the split method provides some control over how many times the pattern is applied, and what is done with any trailing empty elements that might be produced. It is also available via the String class split method.

The limit argument takes on different meanings depending on whether it's less than zero, zero, or greater than zero.

8.7.1. 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). 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. 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:

Friedl,Jeffrey,Eric Francis,America,Ohio,Rootstown

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.

Mastering Regular Expressions
Mastering Regular Expressions
ISBN: 0596528124
EAN: 2147483647
Year: 2004
Pages: 113

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: