Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top