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.

  • kcshafer

    kcshafer Correct answer

    7 years ago

    This should work for you:

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

    --KC

    What {1} does here ?

    Specifies that you are searching for one and only one instance of a comma.

    What if you want to add single quotes to each split item?

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM