Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string with arbitrary number of commas and spaces

Tags:

java

regex

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?

like image 907
Aboutblank Avatar asked Mar 07 '13 20:03

Aboutblank


1 Answers

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]
like image 67
Bohemian Avatar answered Nov 15 '22 20:11

Bohemian