Search code examples
iosregexdatensregularexpression

Regular Expression iOS for Various Date Formats


I am struggling to get my head around some regular expression to match some date formats. Ideally i would like one expression too match every date format possible, i am searching a email for all dates with in the body.

Formats such as:

Wednesday, 6 November 2013
Weds 6th November 2013
Weds 6th Nov 2013

06/11/2013
11/06/2013
06/11/13
11/06/13

6th Nov 2013
6th November 2013

Anyone know of an all in one expression I could use?


Solution

  • Thanks to Wain's answer I'm using this code instead of NSRegularExpression to find dates within a string, hope it might help anyone with a similar problem.

    NSError *error = NULL;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeDate error:&error];
    
    NSArray *matches = [detector matchesInString:string
                                         options:0
                                           range:NSMakeRange(0, [string length])];
    
    for (NSTextCheckingResult *match in matches) {
        
        if ([match resultType] == NSTextCheckingTypeDate) {
            
            NSDate *date = [match date];
            
            NSDateFormatter *formatter;
            NSString        *dateString;
            
            formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
            
            dateString = [formatter stringFromDate:date];
            NSLog(@"Date: %@",dateString);
       
        }
    }