适用于各种日期格式的正则表达式iOS



我很难找到一些正则表达式来匹配一些日期格式。理想情况下,我希望一个表达式也能匹配所有可能的日期格式,我正在搜索电子邮件中的所有日期。

格式如:

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

有人知道我可以用一个集所有于一身的表达方式吗?

感谢Wain的回答,我使用这段代码而不是NSRegularExpression来查找字符串中的日期,希望它能帮助任何有类似问题的人。

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

考虑使用NSDataDetector,它可以配置为扫描日期(NSTextCheckingTypeDate)。此处提供文档。

您可以用多个字符串编写正则表达式
还可以在中测试正则表达式http://regexpal.com它的不同之处在于您删除了例如表达式中的\(\d{2})([./-])

NSError *error = NULL;  
    NSString *expForSlash = @"(\d{2})((/)|(.))(\d{2})((/)|(.))(\d{4}|\d{2})";

NSString *expMonthStrNew = @"(Jan|Feb|Mar(ch)?|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\s?)(\d{2}|\d{1})(,?)(\s?)(\d{4}|\d{2})";
NSString *expForreg  = [NSString stringWithFormat:@"%@|%@", expForSlash, expMonthStrNew];//@"(May|Jun)(\s?)(\d{2})(,?)(\s?)(\d{4})";
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:expForreg
                              options:NSRegularExpressionCaseInsensitive
                              error:&error];

NSArray *matches = [regex matchesInString:tesText options:0 range:NSMakeRange(0, [tesText length])];

改进Neil Faulkner的反应。

如果你想获得本地化格式的日期:

NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeDate error:&error];
NSArray *matches = [detector matchesInString:value
                                     options:0
                                       range:NSMakeRange(0, [value length])];
for (NSTextCheckingResult *match in matches)
{
    if ([match resultType] == NSTextCheckingTypeDate)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.locale = [NSLocale currentLocale];
        formatter.dateStyle = NSDateFormatterShortStyle;
        response = [formatter stringFromDate:[match date]];
    }
}

最新更新