Skip to content Skip to sidebar Skip to footer

Splitting A String By Number Of Delimiters

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

Solution 1:

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.

Solution 2:

You can use

parts=strExample.split("\\s,\\s*");

for your case.

Post a Comment for "Splitting A String By Number Of Delimiters"