简体   繁体   中英

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?

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

You can always use 'rangeOfString:options:range:' for the second one (starting after the 'location' of the first one).

Option 1

- (NSRange)rangeOfQuoteInString:(NSString *)str {
    int firstMatch = [str rangeOfString:@"\""].location;
    int secondMatch = [str rangeOfString:@"\"" options:0 range:NSMakeRange(firstMatch + 1, [str length] - firstMatch - 1)].location;
    return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
}

I hope this is right. Done on my phone at dinner. ;-)

One other thing, though, since range of string likely does a similar implementation, why not iterate the 'char' values in the string and look for matches #1 & #2? Could be as fast or faster.

Option 2

- (NSRange)rangeOfQuoteInString:(NSString *)str {
    int firstMatch = -1;
    int secondMatch = -1;
    for (int i = 0; i < [str length]; i = i + 1) {
        unichar c = [str characterAtIndex:i];
        if (c == '"') {
            if (firstMatch == -1) {
                firstMatch = i;
            } else {
                secondMatch = i;
                break;
            }
        }
    }
    if (firstMatch == -1 || secondMatch == -1) {
        // No full quote was found
        return NSMakeRange(NSNotFound, 0);
    } else {
        return NSMakeRange(firstMatch, secondMatch + 1 - firstMatch);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM