1

I'm trying to separate a string by the use of a comma. However I do not want to include commas that are within quoted areas. What is the best way of going about this in Objective-C?

An example of what I am dealing with is:

["someRandomNumber","Some Other Info","This quotes area, has a comma",...]

Any help would be greatly appreciated.

  • There is no easy solution. This is equivalent to parsing a CSV file which uses the same syntax (quoted string so the field separator can appear in a field value). You may also have to deal with values containing quote characters too. Search for solutions about parsing CSV files. – rmaddy Jun 24 '13 at 22:50
  • Can you split on `@"\",\""` ? I.e. is every string quoted? – Wain Jun 24 '13 at 23:23

1 Answers1

0

Regular expressions might work well for this, depending on your requirements. For example, if you're always trying to match items that are enclosed in double quotes, then the it might be easier to look for the quotes rather than worrying about the commas.

For example, you could do something like this:

NSString *pattern = @"\"[^\"]*\"";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
  options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in matches) {
   NSRange matchRange = [match range];
   NString *substring = [string substringWithRange:matchRange];
   // do whatever you need to do with the substring
}

This code looks for a sequence of characters enclosed in quotes (the regex pattern "[^"]*"). Then for each match it extracts the matched range as a substring.

If that doesn't exactly match your requirements, it shouldn't be too difficult to adapt it to use a different regex pattern.

I'm not in a position to test this code at the moment, so my apologies if there are any errors. Hopefully the basic concept should be clear.

James Holderness
  • 22,721
  • 2
  • 40
  • 52
  • I ended up figuring it out. I phrased the question wrong I think, not everything is enclosed in quotes, which made things more difficult. However your solution does look like it would work for everything enclosed in quotes. I ended up solving this by looking at the string one character at a time, separating everything using the comma or closing brace as object terminators. Then recursively calling the function to analyze nested arrays. – user2517992 Jul 09 '13 at 19:46