Search code examples
objective-cregexnsrange

How can I pull the year out of this NSString?


I have a number of NSStrings of movie titles like this:

@"Accepted (2006)"
@"Blade Runner (1982)"
@"(500) Days of Summer (2009)"
@"RoboCop (1987) - Criterion #23"

I am trying to get the four-digit numeric-only year that is always between ( and ) out of the title.

Whats the proper way to do this? NSRange? RegEx? Something else? Objective-C please, not Swift.


Solution

  • For this it is simpler to use the NSString method: rangeOfString:options: with the option NSRegularExpressionSearch with a look-behind and look-ahead based regex:

    NSRange range = [test rangeOfString:@"(?<=\\()\\d{4}(?=\\))" options:NSRegularExpressionSearch];
    NSString *found = [test substringWithRange:range];
    
    NSLog(@"found: %@", found);
    

    Output:

    found: 2006

    For more information see the ICU User Guide: Regular Expressions