How to split a string by comma and white space
This should work for you:
String x = 'a, b,c';
system.debug(x.split('[,]{1}[\\s]?'));
--KC
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]);