2

I need to split up a string which is separated by commas while preserving any quoted substrings (which may have commas too).

String example:

NSString *str = @"One,Two,\"This is part three, I think\",Four";
for (id item in [str componentsSeparatedByString:@","])
    NSLog(@"%@", item);

This returns:

  • One
  • Two
  • "This is part three
  • I think"
  • Four

The correct result (respecting quoted substrings) should be:

  • One
  • Two
  • "This is part three, I think"
  • Four

Is there a reasonable way to do this, without re-inventing or re-writing quote-aware parsing routines?

Robert Altman
  • 5,355
  • 5
  • 33
  • 51
  • Regular Expressions http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html – Joe Jun 24 '11 at 17:07

2 Answers2

2

Let's think about this a different way. What you have is a comma-seperated string, and you want the fields in the string.

There's some code for that:

https://github.com/davedelong/CHCSVParser

And you'd do this:

NSString *str = @"One,Two,\"This is part three, I think\",Four";
NSArray *lines = [str CSVComponents];
for (NSArray *line in lines) {
  for (NSString *field in line) {
    NSLog(@"field: %@", field);
  }
}
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
0

Here is a C# answer to the same problem.

C# Regex Split - commas outside quotes

You could probably use the same Regex in Objective-C

NSString split Regex with ,(?=(?:[^']*'[^']*')*[^']*$)

Community
  • 1
  • 1
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100