I have string value :

String x = '(My, Test Value, New Other, Value)';

Expected outcome or expected list of string is :

list<string> NewList = new list<string>{'My, Test Value','New Other, Value'};

I had used this approach but it is splitting everything after ','

string x = '(My, Test Value, New Other, Value)';
List<String> lstString = x.removeStart('(').removeEnd(')').trim().split(',');
  • 2
    How would your splitting algorithm possibly know that My is not a distinct value? If you want to use a comma delimiter, it seems like My, Test Value is an incorrect expectation. Please edit your post to clarify your requirements.
    – Adrian Larson
    Jun 15 '21 at 20:26

That's how the split() method works. You give it a delimiter, and it creates a new item in the resulting list after every instance of the delimiter that it encounters.

The delimiter is supposed to be something that separates entries but does not appear within entries.

If you have control over this string value that you're working with, the easiest fix here (well, easiest from the perspective of the code that is consuming this string) is to change the string so that the delimiter actually serves as a delimiter (semicolons are a popular choice).

If you can't control the string you're consuming, then split() is not the right tool for the job.

If there is a regular pattern, like every second comma will always mean it's a new value, then you could get by with a combination of replaceAll() (to get a proper delimiter) followed by split().

String x = 'My, Test Value, New Other, Value';
List<String> badResult = x.split(',');

system.debug(badResult.size()); // prints '4'

// () = a capturing group
// [^,]+,[^,]+ = one or more of any non-comma character, followed by a comma, followed by one or
//   more of any non-comma character
// $1; = print the stuff inside capturing group #1, followed by an ';'
// We can then split on that semicolon
List<String> goodResult = x.replaceAll('([^,]+,[^,]+),', '$1;').split(';');

system.debug(goodResult.size()); // prints 2

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.