Idea behind solution:
You want to split your string into an array on every occurrence of ,
, accounting for data contained within "
as a single item.
To do this you have to use the global split
function with a regex pattern.
Code sample:
extension String
{
func splitCommas() -> [Stirng] {
let pattern = ",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)" //regex pattern for commas that are not within quotes
if let regex = try? NSRegularExpression(pattern: pattern, options: []) {
let string = self as NSString
return regex.matches(in:inputString, range: NSMakeRange(0, inputString.utf16.count)).map {
string.substring(with: $0.range).replacingOccurrences(of: ",", with: "") //removing all instances of commas
}
}
return []
}
}
Hope this helps! ;)
Updates
Updated code to more modern example.
Also implemented function as a String extension for usability within all of the String variables.