简体   繁体   中英

How to find occurrence of a format in NSString

I am reading a feed, and need to find the occurrence of a string format, for example, in "Feed for 03/02/2012". Now this date will always be of the format: %@/%@/%@. I need to find is this format occurs, and thus extract the date. The date and month can be any, so i don't have a specific date to search for. I searched in the docs, could not find it. Only option possible to me seems to take all 12 combinations of a month like "/12/", and find the occurrence of any of these.

Is there any better approach?

You can use regular expressions:

NSString *feed = @"Feed for 03/02/2012";

NSError *error;

NSRegularExpression *regex = [NSRegularExpression         
    regularExpressionWithPattern:@"([0-9]{1,2})/([0-9]{1,2})/([0-2][0-9]{3})"
    options:NSRegularExpressionCaseInsensitive
    error:&error];

[regex enumerateMatchesInString:feed options:0 range:NSMakeRange(0, [feed length])    usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
    NSString *month = [feed substringWithRange:[match rangeAtIndex:1]];
    NSString *day = [feed substringWithRange:[match rangeAtIndex:2]];
    NSString *year = [feed substringWithRange:[match rangeAtIndex:3]];
    //...
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM