2

我正在努力了解一些正则表达式以匹配某些日期格式。理想情况下,我希望一个表达式也可以匹配每种日期格式,我正在电子邮件中搜索正文中的所有日期。

格式如:

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

有人知道我可以使用的多合一表达吗?

4

4 回答 4

5

感谢 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);
   
    }
}
于 2013-07-06T14:15:57.043 回答
3

考虑使用NSDataDetectorwhich 可以配置为扫描日期 ( NSTextCheckingTypeDate)。文档在这里

于 2013-07-06T13:17:03.670 回答
0

您可以使用多个字符串编写正则表达式,
也可以在 http://regexpal.com中测试正则表达式, 因为您删除了表达式中的 \,例如 (\d{2})([./-])(\d {2})([./-])(\d{2,4})

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])];
于 2015-05-07T07:38:58.317 回答
0

改善尼尔福克纳的反应。

如果您想使用本地化格式获取日期:

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]];
    }
}
于 2016-09-08T12:48:24.257 回答