If I have a NSString at looks like:
2-13-2014 Norway vs Canada Per 1 20-00 2
Its being parsed and the dates will change
How do I make it turn into
Norway vs Canada Per 1
In other words, drop the date and extra characters at the end.
Iv'e used:
NSArray * dateComponents = [cleanString
componentsSeparatedByCharactersInSet:
[NSCharacterSet
characterSetWithCharactersInString:@"-"]];
cleanString = [NSString stringWithFormat:@"%@", [dateComponents objectAtIndex:2]];
output:
2014 Norway vs Canada Per 1 20
Thanks
If the format is consistently in a particular format you can use regular expressions. For example, if the format is always:
dd-dd-dddd xxxxxxxxxxxxxxxxx dd-dd d
Thus if you just want the Norway vs Canada Per 1
from your example (i.e. the xxxxxxxxxxxxxxxxx
from above), you could:
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);
}
If you need help deciphering the regex, I might refer you to the NSRegularExpression
documentation.