2013-07-06 103 views
2

我很努力地讓我的頭在一些正則表達式中匹配一些日期格式。理想情況下,我希望一個表達式能夠匹配每個可能的日期格式,我正在搜索正文中的所有日期的電子郵件。各種日期格式的正則表達式的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 

任何人都知道的都在同一個表情我可以使用?

+0

可能重複:[正則表達式各種日期格式(http://stackoverflow.com/q/11516129/1578604)。 – Jerry

回答

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

    }} 
+0

謝謝尼爾!這對我來說也是一個完美的解決方案 – Greg

3

考慮使用可配置爲掃描日期的NSDataDetectorNSTextCheckingTypeDate)。 Docs here

+0

非常感謝您似乎檢測大多數日期格式! –

0

可以編寫的正則表達式與幾個串
也可以在 http://regexpal.com 其不同測試的正則表達式,因爲你刪除\在表達式例如 (\ 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])]; 
0

改善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]]; 
    } 
}