Regular Expressions – 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]*"); 

    system.debug('Check'+stringList);

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.

Best Answer

This should work for you:

String x = 'a, b,c';
system.debug(x.split('[,]{1}[\\s]?'));

--KC