1

我正在解析一个通常采用这种格式的字符串:

上午 8:00 - 晚上 9:00

我使用此代码将打开时间与关闭时间分开,并得到一个 2 次数组:

NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
    int idx = [s rangeOfCharacterFromSet:digits].location;
    NSString *timeStr = [s substringFromIndex:idx];
    NSArray *timeStringsArray2 = [timeStr componentsSeparatedByString:@" - "];
    NSLog(@"timeStringsArray2 %@", timeStringsArray2);

问题是某些时间字符串写得不正确,如下所示:

上午 8:00 - 晚上 9:00

这个简单的错误会引发以下错误:

-[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

因为它无法分离时间字符串中的项目。我确信即使我让客户修复了这些错误,他们有时也会重新插入包含此错误的记录。我该如何考虑这两种情况?

4

3 回答 3

2

这正是正则表达式所针对的问题。

下面的代码会将一个字符串timeString分成两个不同的时间firstTime,并且secondTime在您描述的情况下,无论是正确还是错误地编写。它将处理多个空格、没有空格或任何空白字符而不是空格,这使得它比假设您在破折号的任一侧最多有一个空格更健壮一点:

NSString *timeString = @"8:00AM - 9:00PM";

NSString *pattern = @"\\s*-\\s*";//Matches zero or more whitespace characters surrounding a dash character

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                       options:0 error:NULL];

NSTextCheckingResult *match = [regex firstMatchInString:timeString
                                                options:0
                                                  range:NSMakeRange(0, [timeString length])];
if (match) {
    NSRange matchRange = [match range];
    NSString* firstTime = [timeString substringToIndex:matchRange.location];
    NSString* secondTime = [timeString substringFromIndex:matchRange.location + matchRange.length];

    NSLog(@"First time: %@", firstTime);
    NSLog(@"Second time: %@", secondTime);
}
于 2013-08-11T04:38:40.217 回答
2

While we are at it - don't rely on whitespace being here and there! To fix your code, just remove all whitespace first, then separate by the hyphen (without the spaces, again):

NSString *timeStr = @"8:00AM- 9:00PM";
NSString *stripped = [timeStr stringByReplacingOccurrencesOfString:@" " withString:@""];
NSArray *times = [stripped componentsSeparatedByString:@"-"];

And that's it.

于 2013-08-11T04:43:18.617 回答
1

很抱歉,我不知道如何使您的代码正常工作,但我只是测试了我会这样做的方式:

NSString *testString = [NSString stringWithFormat:@"%@%@", @"8:00AM - 9:00PM", @"*"];
NSScanner *scanner = [NSScanner scannerWithString:testString];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@" -"]];
NSString *startTime = nil, *endTime = nil;
while ([scanner scanUpToString:@"-" intoString:&startTime] && [scanner scanUpToString:@"*" intoString:&endTime]) {
    // Process the row as needed.
    NSLog(@"Start time:%@, End time:%@", startTime, endTime);
}

正确产生输出:

2013-08-11 00:29:20.665 StackOverflowTests[15213:c07] 开始时间:上午 8:00,结束时间:下午 9:00

它还会在上午 8:00 到晚上 9:00 产生完全相同的结果,所以我希望这会有所帮助。

于 2013-08-11T04:33:34.650 回答