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.


This should work for you:

String x = 'a, b,c';


  • What {1} does here ? – SFDC Geek Sep 5 '14 at 16:04
  • 1
    Specifies that you are searching for one and only one instance of a comma. – kcshafer Sep 5 '14 at 18:03
  • What if you want to add single quotes to each split item? – Jonathan Brooks Dec 23 '14 at 20:00

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]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.