2017-02-15 50 views

回答

0

這種嘗試:

let name = "uploads/4/jobs/2017-02-15-05-17-05pmThe_Wolf_of_Wall_Street_-_Jordan_Belfort.pdf" 
var names = name.components(separatedBy: "/") 
let lastComponent = names[names.count - 1] 

var nameOfFile:String = "" 
let pm = lastComponent.components(separatedBy: "pm") 
let am = lastComponent.components(separatedBy: "am") 
if(pm.count > 1){ 
    nameOfFile = pm[1] 
} else if(am.count > 1){ 
    nameOfFile = am[1] 
} 
print(nameOfFile) 
+1

如果文件名包含「2017-02-15-05-17-05pmAbc-am.pdf」,那該怎麼辦呢? –

+0

您可以刪除最後一個路徑組件或使用: var fileNameComponents = filename.components(separatedBy:「。」) let fileNameOnly = fileNameComponents [0] –

0

你可以試試下面的代碼爲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); 
} 

希望這有助於。

+0

如果文件名包含'2017-02-15-05-17 -05pmAbc-am.pdf'呢? –

0

如果您的網址將始終遵循開始命名格式。

let urlStr = "uploads/4/jobs/2017-02-15-05-17-05pmThe_Wolf_of_Wall_Street_-_Jordan_Belfort.pdf" 
    let indexStart = urlStr.index(urlStr.startIndex, offsetBy: +36) 
    let str = urlStr.substring(from: indexStart) 
    let indexEnd = str.index(str.endIndex, offsetBy: -4) 
    let name = str.substring(to: indexEnd) 
相關問題