Neil Faulkner Neil Faulkner - 1 year ago 71
iOS Question

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


6th Nov 2013
6th November 2013

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

Answer Source

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
                                       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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download