Reputation: 2048
I have a string 2000-01-01T10:00:00Z
I want to pull time time out of that string: 10:00
Can anyone tell me how to do it using NSRegularExpression
I tried the following code but it isn't working (returning no results)
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\d{2}:\d{2})" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *newSearchString = [regex firstMatchInString:opening_time options:0 range:NSMakeRange(0, [opening_time length])];
Where opening_time
is "2000-01-01T10:00:00Z"
Upvotes: 2
Views: 2165
Reputation: 24476
Use NSDateFormatter
. It looks like you're probably getting this date from a Rails web service? Try this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'Z'"];
NSDate *date = [dateFormatter dateFromString:opening_time];
NSDateComponents *components = [[NSCalendar currentCalendar]
components:kCFCalendarUnitHour fromDate:date];
NSInteger hour = [components hour]
// Hour should now contain 10 with your sample date
If you want to get any other components, change your components parameter adding the flags for the components you want to extract. Something like this
NSDateComponents *components = [[NSCalendar currentCalendar]
components:kCFCalendarUnitHour | kCFCalendarUnitMinute
fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
Upvotes: 2
Reputation: 318934
If all you really want is the 10:00 part of this fixed format string, why not avoid the regular expression and simply get the substring:
NSString *timeStr = [opening_time substringWithRange:NSMakeRange(11, 5)];
Of course you might consider parsing the string into an NSDate using an NSDateFormatter with the specified format. Make sure the date formatter's locale is set to en_US_POSIX since it is fixed format and not user focused.
The approach you take depends on what you will do with the time you extract. If you want to display it to the user then you want to use an NSDateFormatter so you can format it properly for the user's locale.
Upvotes: 0
Reputation: 727027
I think you need to double the slashes in front of your \d
s:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{2}:\\d{2})" options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult *newSearchString = [regex firstMatchInString:opening_time options:0 range:NSMakeRange(0, [opening_time length])];
NSString *substr = [opening_time substringWithRange:newSearchString.range];
NSLog(@"%@", substr);
This prints 10:00
Upvotes: 10