Getting NSRange of string between quotations?

ios, iphone, objective-c

Solution

You could use a regular expression for this:

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([\"])(?:\\\\\\1|.)*?\\1" options:0 error:&error];

NSRange range = [regex rangeOfFirstMatchInString:myString options:0 range:NSRangeMake(0, [myString length]];

Don't forget to check for errors ;)

Problem

I have a string: He said "hello mate" yesterday. I want to get an NSRange from the first quotation to the last quotation. So I tried something like this: ``` NSRange openingRange = [title rangeOfString:@"\""]; NSRange closingRange = [title rangeOfString:@"\""]; NSRange textRange = NSMakeRange(openingRange.location, closingRange.location+1 - openingRange.location); ``` But I'm not sure how to make it distinguish between the first quote and the second quote. How would I do this?

Original source