iphoneobjective-cregexcocoa-touchnsdatadetector

How can I use a custom NSDataDetector to detect certain regex patterns?


I am currently using NSDataDetectors to find links:

-(void)setBodyText
{
    NSString* labelText = [[message valueForKey:@"body"]gtm_stringByUnescapingFromHTML];

    NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
    NSArray *matches = [linkDetector matchesInString:labelText options:0 range:NSMakeRange(0, [labelText length])];
    for (NSTextCheckingResult *match in matches) {
        if ([match resultType] == NSTextCheckingTypeLink) {
            NSURL *url = [match URL];
            [bodyLabel addCustomLink:url inRange:[match range]];
            NSLog(@"found URL: %@", url);
        }
    }

    [bodyLabel setText:labelText];
    [Utils alignLabelWithTop:bodyLabel];
}

How can I use NSDataDetectors to parse @ for example:

"Hello @sheehan, you are cool"

I want it to be able to detect @sheehan

NOTE: I want to use NSDataDetector's or regex pattern matching. No custome Labels or controls etc.


Solution

  • You could just use this method that uses NSRegularExpression to find @name matches.

    - (NSMutableArray *)findTwitterHandle:(NSString *)text {
    
        NSError *error = nil;
    
        NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(@[a-zA-Z0-9_]+)" 
                                                                      options:NSRegularExpressionCaseInsensitive 
                                                                        error:&error];
    
        if (error != nil) {
    
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                                                        message:[error localizedDescription] 
                                                       delegate:nil 
                                              cancelButtonTitle:nil 
                                              otherButtonTitles:@"Ok", nil];
    
            [alert show];
    
            [alert release];
    
        }
    
        NSMutableArray *siteNames = [NSMutableArray array];
    
        NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])];
    
        for (NSTextCheckingResult *result in matches) {
    
            [siteNames addObject:[text substringWithRange:result.range]];
    
        }
    
        [regex release];
    
        return siteNames;
    
    }
    

    This method will return a NSMutableArray with all the matching strings.