objective-c - 使用 NSRegularExpression 命名捕获组

标签 objective-c regex cocoa nsregularexpression

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/

相关文章:

python - re.search 和 re.match 有什么区别?

ios - stringWithFormat 在 LLDB 中不起作用

iphone - 在 iPhone 中将事件添加到默认日历时出错

objective-c - 在类别中添加初始值设定项

Javascript - 在正则表达式中使用连接字符串

objective-c - 如何在 cocoa/objective-c 中注册新模式?

cocoa - 带有静态图像的弹出按钮(Cocoa OSX)

iphone - UIImagePickerController - 设置最大视频持续时间

objective-c - 保持 NSTableCellView 处于焦点

python - 返回下一行匹配的搜索字符串