Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting NSRange of string between quotations?

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?

like image 304
Snowman Avatar asked Feb 21 '23 14:02

Snowman


1 Answers

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 ;)

like image 176
JustSid Avatar answered Mar 04 '23 10:03

JustSid