Apple開發_提取出字串中長度為24的UUID子字串

CH520發表於2024-08-02
@interface NSString (UUIDExtraction)

- (NSArray<NSString *> *)extract_UUID_Strings;

@end

@implementation NSString (UUIDExtraction)

// 提取出字串中長度為24的UUID子字串
- (NSArray<NSString *> *)extract_UUID_Strings {
    // 定義一個正規表示式來匹配UUID(這裡假設沒有連字元)
    NSString *uuid_pattern = @"[0-9A-F]{24}";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:uuid_pattern
                                                                           options:NSRegularExpressionCaseInsensitive error:&error];
    
    if (error) {
        NSLog(@"Error creating regular expression: %@", error.localizedDescription);
        return nil;
    }
    
    // 執行匹配並收集結果
    NSArray *matches = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    NSMutableArray *uuids = [NSMutableArray array];
    
    for (NSTextCheckingResult *match in matches) {
        NSRange match_range = [match range];
        NSString *uuid = [self substringWithRange:match_range];
        [uuids addObject:uuid];
    }
    
    return uuids;
}

@end

相關文章