0

如果我有一个 NSString 看起来像:

2-13-2014 Norway vs Canada Per 1 20-00 2

它正在被解析并且日期会改变

我如何让它变成

Norway vs Canada Per 1

换句话说,把日期和多余的字符放在最后。

我用过:

NSArray * dateComponents = [cleanString
                            componentsSeparatedByCharactersInSet:
                            [NSCharacterSet
                             characterSetWithCharactersInString:@"-"]];

cleanString = [NSString stringWithFormat:@"%@", [dateComponents objectAtIndex:2]]; 

输出:

2014 Norway vs Canada Per 1 20

谢谢

4

2 回答 2

1

按空格分割。然后删除第一个组件和最后两个组件。

NSString *input = @"2-13-2014 Norway vs Canada Per 1 20-00 2";

NSArray *words = [input componentsSeparatedByString:@" "];
words = [words subarrayWithRange:NSMakeRange(1, words.count - 3)];
NSString *output = [words componentsJoinedByString:@" "];
于 2014-08-21T20:18:42.290 回答
0

如果格式始终采用特定格式,则可以使用正则表达式。例如,如果格式始终为:

dd-dd-dddd xxxxxxxxxxxxxxxxx dd-dd d

因此,如果您只想要Norway vs Canada Per 1示例中的(即xxxxxxxxxxxxxxxxx上面的),您可以:

NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\\s*\\d{1,2}-\\d{1,2}-\\d{2,4}\\s+(.+)\\s+\\d{1,2}-\\d{1,2}\\s*\\d\\s*$" options:0 error:&error];

NSTextCheckingResult *result = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (result) {
    NSRange range = [result rangeAtIndex:1];             // find the NSRange for the stuff in the parentheses
    NSString *found = [string substringWithRange:range]; // get the string for that range
    NSLog(@"found = '%@'", found);
}

如果您在破译正则表达式时需要帮助,我可能会向您推荐NSRegularExpression文档

于 2014-08-21T21:06:47.920 回答