你可以試試下面的代碼爲Objective-C
NSString* string = @"uploads/4/jobs/2017-02-15-05-17-05pmThe_Wolf_of_Wall_Street_-_Jordan_Belfort.pdf";
NSArray* array = [string componentsSeparatedByString:@"/"];
NSString* lastElement = [array lastObject];
NSArray* finalArrayForPM = [lastElement componentsSeparatedByString:@"pm"];
NSArray* finalArrayForAM = [lastElement componentsSeparatedByString:@"am"];
if (finalArrayForPM.count > 1) {
NSString* fileName = [[finalArrayForPM lastObject] stringByDeletingPathExtension];
NSLog(@"The fileName is %@",fileName);
} else if (finalArrayForAM.count > 1) {
NSString* fileName = [[finalArrayForAM lastObject] stringByDeletingPathExtension];
NSLog(@"The fileName is %@",fileName);
}
希望這有助於。
如果文件名包含「2017-02-15-05-17-05pmAbc-am.pdf」,那該怎麼辦呢? –
您可以刪除最後一個路徑組件或使用: var fileNameComponents = filename.components(separatedBy:「。」) let fileNameOnly = fileNameComponents [0] –