The String.split(String regex, int limit)
is close to what you want. From the documentation:
The limit
parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
- If the limit
n
is greater than zero then the pattern will be applied at most n - 1
times, the array's length will be no greater than n
, and the array's last entry will contain all input beyond the last matched delimiter.
- If
n
is non-positive then the pattern will be applied as many times as possible and the array can have any length.
- If
n
is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Here's 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 = "a-b-c-d---";
dump(text.split("-"));
// prints "[a][b][c][d]"
dump(text.split("-", 2));
// prints "[a][b-c-d---]"
dump(text.split("-", -1));
// [a][b][c][d][][][]
}
A partition that keeps the delimiter
If you need a similar functionality to the partition, and you also want to get the delimiter string that was matched by an arbitrary pattern, you can use Matcher
, then taking substring
at appropriate indices.
Here's 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 regex \d+
of course is any digit character (\d
) repeated one-or-more times (+
).