获取包含在NSString中的文件的扩展
我有一个NSMutable字典,它包含fileone.doc或filetwo.pdf的简单形式中的文件ID及其文件名+扩展名。我需要确定在UITableView中正确显示相关图标的文件类型。这是我迄今为止所做的。获取包含在NSString中的文件的扩展
NSString *docInfo = [NSString stringWithFormat:@"%d", indexPath.row]; //Determine what cell we are formatting
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string
我写了两个正则表达式来确定我在看什么类型的文件,但他们从来没有返回一个积极的结果。我之前没有在iOS编程中使用过正则表达式,所以我不完全确定我是否正确地做了这件事,但我基本上从类描述页面复制了代码。
NSError *error = NULL;
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])];
NSLog(@"How many matches were found? %@", numMatch);
我的问题是,有没有更简单的方法来做到这一点?如果不是,我的正则表达式是不正确的?最后,如果我不得不使用它,运行时间是否昂贵?我不知道用户将有多少文件的平均数量。
谢谢。
//NSURL *url = [NSURL URLWithString: fileType];
NSLog(@"extension: %@", [fileType pathExtension]);
编辑你可以使用NSString的pathExtension
感谢David巴里
您可以直接在字符串调用pathExtension,无需首先创建一个NSURL。 – 2012-02-12 00:01:15
为什么你刚才撕开了上面的答案,然后记入他? – 2014-03-30 12:52:48
尝试使用[文件pathExtension]到获取文件的扩展名。
试试这个:
NSString *fileName = @"resume.doc";
NSString *ext = [fileName pathExtension];
在斯威夫特3,你可以使用一个扩展:
extension String {
public func getExtension() -> String? {
let ext = (self as NSString).pathExtension
if ext.isEmpty {
return nil
}
return ext
}
}
试试这个,它为我工作。
NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
呵呵,不知道NSString有'pathExtension'属性 – remy 2012-02-12 00:02:00
Objective-C只是让事情变得如此简单;我不需要想到这种困难的解决方案!谢谢大卫。 – TheJer 2012-02-13 00:40:16
我很高兴我没有尝试自己做这个功能 – Will 2012-10-12 14:23:09