Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split expression by comma and space in Java?

Tags:

java

regex

split

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*")
like image 295
Jenya Kirmiza Avatar asked Mar 03 '18 22:03

Jenya Kirmiza


People also ask

How do you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

How do you split with whitespace?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

What does split \\ s+ do in Java?

split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.

Can we split a string with dot in Java?

To split a string with dot, use the split() method in Java. str. split("[.]", 0); The following is the complete example.


2 Answers

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

like image 157
Aubin Avatar answered Oct 21 '22 04:10

Aubin


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]
like image 35
Przemysław Moskal Avatar answered Oct 21 '22 04:10

Przemysław Moskal