The reason you are getting the leading empty string is because your delimiter (a series of non-digit characters) leads the string. It would be the same reason why:
String s = ",";
String[] splitResult = s.split(",");
would give splitResult to be ["",""]. Every time there is a delimiter, even if it is at the beginning or end of the string, it is splitting two tokens in the string. If the delimiter is at the beginning of the string, at the end of the string, or if there are two adjacent delimiters (which wouldn't happen in your case because of the greedy + quantifier, but would happen in the above case with String s = ",,";), then the split result will have empty strings.
An easy way to solve your problem is to filter out the empty strings. You know it can only appear at the front or back of your input string, so it is not really a problem. E.g.:
- Check the first and last string in
nums. If they are empty, remove them.
- Use regex to search for the digits, not split by the non-digits.
- Remove any leading/trailing non-digits before running your code.
I'm not too fluent in Java, but I'm sure there's probably some cleaner Java idiom to do this with the code you've provided.