Split a string with arbitrary number of commas and spaces
java, regex
Solution
You need two steps, but only one line:
String[] values = input.replaceAll("^[,\\s]+", "").split("[,\\s]+");
The call to `replaceAll()` removes leading separators. The split is done on any number of separators.
The behaviour of `split()` means that a trailing blank value is ignored, so no need to trim trailing separators before splitting.
Here's a test:
public static void main(String[] args) throws Exception {
String input = ",A,B,C,D, ,,,";
String[] values = input.replaceAll("^[,\\s]+", "").split("[,\\s]+");
System.out.println(Arrays.toString(values));
}
Output:
[A, B, C, D]
Problem
I have a String that I'm trying to turn into a list but I get empty entries. ``` ",A,B,C,D, ,,," returns [, A, B, C, D, , , ,] ``` I want to remove all "empty" commas: ``` [A, B, C, D] ``` I'm trying ``` current.split(",+\\s?") ``` which does not produce the result I want. What regex should I use instead?