gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:31:20 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com