我怎样才能从这个 NSString 中提取年份?

How can I pull the year out of this NSString?

我有很多像这样的 NSStrings 电影片名:

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

我正在尝试从标题中获取始终介于 ( 和 ) 之间的 four-digit numeric-only 年份。

执行此操作的正确方法是什么? NS范围?正则表达式?还有别的吗? Objective-C 请不要 Swift.

使用基于环视的正则表达式。

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

使用捕获组。

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

由于 () 是正则表达式元字符,您需要转义这些字符才能匹配文字 () 符号。

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

为此,使用 NSString 方法更简单:rangeOfString:options:使用选项 NSRegularExpressionSearch 以及基于后视和前视的正则表达式:

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

NSLog(@"found: %@", found);

输出:

found: 2006

有关详细信息,请参阅 ICU 用户指南:Regular Expressions