1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

2 Answers2

4

Use a lookaround based regex.

"(?<=\\()\\d{4}(?=\\))"

or

Use capturing group.

"\\((\\d{4})\\)"

Since (, ) are regex meta-characters, you need to escape those in-order to match the literal ( or ) symbols.

ie

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\((\\d{4})\\)" options:0 error:NULL];
NSString *str = @"Accepted (2006)";
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

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

zaph
  • 111,848
  • 21
  • 189
  • 228