NSRegularExpression
是否支持命名捕获组?从the documentation 看起来不像,但我想在探索替代解决方案之前进行检查。
最佳答案
iOS 不支持命名分组,正如我所见,您所能做的就是利用 Enum
:
枚举:
typedef enum
{
kDayGroup = 1,
kMonthGroup,
kYearGroup
} RegexDateGroupsSequence;
示例代码:
NSString *string = @"07-12-2014";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{2})\\-(\\d{2})\\-(\\d{4}|\\d{2})"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:string
options:0
range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
NSString *day = [string substringWithRange:[match rangeAtIndex:kDayGroup]];
NSString *month = [string substringWithRange:[match rangeAtIndex:kMonthGroup]];
NSString *year = [string substringWithRange:[match rangeAtIndex:kYearGroup]];
NSLog(@"Day: %@, Month: %@, Year: %@", day, month, year);
}
关于objective-c - 使用 NSRegularExpression 命名捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24814974/