John Baum John Baum - 4 years ago 67
Java Question

Split a string but retain first delimiter

I have a string in the form

. Is there a regex or a simple way to capture this into a String array of the form
[/A, B, C, D]
? Essentially, split on "/" but retain the first instance of the delimiter? I can be guaranteed that the input string will have "/" as the first character and at least one "/" following the first. My attempt has been this so far:

private String[] customSplit(String input) {
if (!input.startsWith("/")) {
input = "/" + input;

String[] output = input.split("/");
output[1] = "/" + output[1];
return output;

The above is a bit clunky though (and has an empty "" spot at index 0) so any suggestions?

Answer Source

You can use a negative lookahead in split to avoid split on first delimiter:

String[] toks = "/A/B/C/D".split("(?!^)/");
//=> [/A, B, C, D]

Here (?!^) is a negative lookahead that will skip start position for delimiter /

RegEx Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download