String.split(String regex, int limit) is close to what you want. From the documentation:
The limit parameter controls the number of uses of the template and, therefore, affects the length of the resulting array.
- If the limit
n greater than zero, the pattern will be applied no more than n - 1 times, the length of the array will be no more than n , and the last record of the array will contain all the input data for the last Corresponding separator. - If
n not positive, the pattern will be applied as many times as possible, and the array can be of any length.- If
n is zero, the template will be applied as many times as possible, the array can be of any length, and the final empty lines will be discarded.
Here is an example to show these differences ( as seen on ideone.com ):
static void dump(String[] ss) { for (String s: ss) { System.out.print("[" + s + "]"); } System.out.println(); } public static void main(String[] args) { String text = "abcd---"; dump(text.split("-")); // prints "[a][b][c][d]" dump(text.split("-", 2)); // prints "[a][bcd---]" dump(text.split("-", -1)); // [a][b][c][d][][][] }
The section containing the delimiter
If you need similar functionality for a section, and you also want to get a separator string that was matched by an arbitrary pattern, you can use Matcher , then take a substring with the corresponding indexes.
Here is an example ( as seen on ideone.com ):
static String[] partition(String s, String regex) { Matcher m = Pattern.compile(regex).matcher(s); if (m.find()) { return new String[] { s.substring(0, m.start()), m.group(), s.substring(m.end()), }; } else { throw new NoSuchElementException("Can't partition!"); } } public static void main(String[] args) { dump(partition("james007bond111", "\\d+")); // prints "[james][007][bond111]" }
The regular expression \d+ , of course, is any digit character ( \d ) repeated one or more times ( + ).
source share