如何从NSString
中提取分钟和秒?例子:
3'15" or 3' 15" (3 minutes 15 seconds)
28" (28 seconds)
2' (2 minutes)
50 (default is in seconds, 50 seconds)
并存储到两个NSInteger
s?
答案 0 :(得分:0)
并不完全相信RegEx匹配是从字符串中读取数字的最佳方式,但这是一个有效的代码片段:
NSString *str = @"12'34\"";
NSString *minutePattern = @"[[:digit:]]+'";
NSString *secondPattern = @"[[:digit:]]+\"?";
NSRange minuteRange = [str rangeOfString: minutePattern options: NSRegularExpressionSearch];
NSRange secondStartRange;
NSString *minuteString = @"";
if ( minuteRange.location != NSNotFound)
{
minuteString = [str substringWithRange: minuteRange];
NSUInteger secondStartPt = NSMaxRange(minuteRange);
secondStartRange = NSMakeRange(secondStartPt, str.length - secondStartPt);
}
else {
secondStartRange = NSMakeRange(0, str.length);
}
NSRange secondRange = [str rangeOfString: secondPattern
options: NSRegularExpressionSearch
range: secondStartRange];
NSString *secondString = @"";
if ( secondRange.location != NSNotFound)
{
secondString = [str substringWithRange: secondRange];
}
NSInteger minutes = [minuteString integerValue];
NSInteger seconds = [secondString integerValue];
NSLog(@"Minutes: %d, seconds: %d", minutes, seconds);
请注意,它会将5'21
之类的字符串解析为5分21秒,不确定这是否是您想要的,但可以通过额外的测试来修复。
答案 1 :(得分:0)
NSArray *data = @[@"3'15\"", @"3' 15\"", @"28\"", @"2'", @"50"];
NSString *pattern = @"(\\d++')|(\\d++(\"{0,1})$)";
NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
for (NSString *string in data) {
NSInteger mi = 0;
NSInteger ss = 0;
NSArray *match = [regExp matchesInString:string options:0 range:NSMakeRange(0,string.length)];
for (NSTextCheckingResult *result in match) {
NSString *value = [string substringWithRange:result.range];
if ([value hasSuffix:@"'"]) {
mi = [value integerValue];
} else {
ss = [value integerValue];
}
}
NSLog(@"%@ - %d %d",string,mi,ss);
}