Ad

Splitting A String By Number Of Delimiters

- 1 answer

I am trying to split a string into a string array, there might be number of combinations, I tried:

String strExample = "A, B";
//possible option are:

1. A,B 
2. A, B
3. A , B
4. A ,B

String[] parts;
parts = strExample.split("/"); //Split the string but doesnt remove the space in between them so the 2 item in the string array is space and B ( B)
parts = strExample.split("/| ");
parts = strExample.split(",|\\s+");

Any guidance would be appreciated

Ad

Answer

To split with comma enclosed with optional whitespace chars you may use

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

The \s*,\s* pattern matches

  • \s* - 0+ whitespaces
  • , - a comma
  • \s* - 0+ whitespaces

In case you want to make sure there are no leading/trailing spaces, consider trim()ming the string before splitting.

Ad
source: stackoverflow.com
Ad