Following is a string:
'First Name','Last Name','Account Name','Email','Title','Description'
and I want it to split with ",'"
(comma and single quotation mark).
Try with this
First remove all single quotes and then split by comma
String str = '\'First Name\',\'Last Name\',\'Account Name\',\'Email\',\'Title\',\'Description\'';
System.debug('===str==='+str);
for(String strFinal: str.replace('\'', '').split(','))
{
System.debug('===Final val==='+strFinal);
}
If we are sure single quotes will be start and end of string then we can remove using string method
for(String strFinal: str.split(','))
{
System.debug('===Final val==='+strFinal.removeStart('\'').removeEnd('\''));
}
',\''
. That would give exactly that outcome that has been asked in question, and it does not have any data loss (in string). Of course, that is pretty easy to do further processing by removing extra quotes if needed. but again -- there would be no data loss or no extra string created
split(',\'')
then this will not give the correct output(I have tested, this contain single quotes end of string).. One more solution I have added in my answer check..
Commented
Apr 11, 2016 at 14:26
"\'Test, string\',\'test, so test\''
, those would fail. There is nowhere asked to have those values with/without quotes. Just question about how to split. again, split on ',\''
would do the magic, and then, if needed, you can remove extra quotes from begin and end. Splitting just on comma would produce extra string and make wrong output
I tried following code and it works fine.
String str = '\'First Name\',\'Last Name\',\'Account Name\',\'Email\',\'Title\',\'Description\'';
List<String> splitList = str.split(',\'');
for(String str : splitList)
System.debug(str.replace('\'',''));