【问题标题】:Regular Expression iOS for Various Date Formats适用于各种日期格式的正则表达式 iOS
【发布时间】:2013-07-06 12:59:45
【问题描述】:
我很难理解一些正则表达式来匹配一些日期格式。理想情况下,我希望一个表达式也匹配所有可能的日期格式,我正在电子邮件中搜索正文中的所有日期。
格式如:
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
有人知道我可以使用的多合一表达式吗?
【问题讨论】:
标签:
ios
regex
date
nsregularexpression
【解决方案1】:
感谢 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);
}
}
【解决方案2】:
考虑使用NSDataDetector,它可以配置为扫描日期(NSTextCheckingTypeDate)。文档here.
【解决方案3】:
你可以用多个字符串编写正则表达式
你也可以测试正则表达式
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])];
【解决方案4】:
改善尼尔福克纳的反应。
如果您想获取本地化格式的日期:
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]];
}
}