Jenya Kirmiza
Jenya Kirmiza

Reputation: 711

How to split expression by comma and space in Java?

For instance, source data:

some blabla, sentence, example

Awaited result:

[some,blabla,sentence,example]

I can split by comma, but don't know how to split by coma and space at the same time?

My source code, so far:

string.split("\\s*,\\s*")

Upvotes: 10

Views: 32334

Answers (2)

Aubin
Aubin

Reputation: 14853

You may use a set of chars as separator as described in Pattern

String string = "One step    at,,a, time ,.";
System.out.println( Arrays.toString( string.split( "[\\s,]+" )));

Output:

[One, step, at, a, time, .]

\s : A whitespace character: [ \t\n\x0B\f\r]

[abc] : a, b, or c (simple class)

Greedy quantifiers X+ : X, one or more times

Upvotes: 17

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

Solution:

String.split("[ ,]+"); // split on on one or more spaces or commas

[] - simple character class

[, ] - simple character class containing space or comma

[ ,]+ - space or comma showing up one or more times

Example:

String source = "A B    C,,D, E ,F";
System.out.println(Arrays.toString(source.split("[, ]+")));

Output:

[A, B, C, D, E, F]

Upvotes: 14

Related Questions