Split NSString preserving quoted substrings
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 par开发者_C百科sing routines?
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);
}
}
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 ,(?=(?:[^']*'[^']*')*[^']*$)
精彩评论