How to split a string by comma and white space

I have a string, I want to separate it by ‘,’ and white Space, if it has any.

This is what I have done :

  String s = 'Donate, Pricing,BOM';

    List<String> stringList = s.split(",[s]*"); 


Check(Donate,  Pricing, BOM)

But I want Check(Donate, Pricing, BOM)

I am getting error :

Invalid string literal ‘,[s]*’. Illegal character sequence ‘s’ in
string literal.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This should work for you:

String x = 'a, b,c';


Method 2

The square brackets (Character Classes) are not necessary for the pattern. Also using the * (zero or more times) operator over ? (once or not at all) operator will allow for the scenario where more than one space might be after the comma.

String x = 'a, b,c,  d';
String[] result = x.split(',\s*');

System.assertEquals(4, result.size());
System.assertEquals('a', result[0]);
System.assertEquals('b', result[1]);
System.assertEquals('c', result[2]);
System.assertEquals('d', result[3]);

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x