我有一个NSMutable字典,它包含文件ID及其文件名+扩展名,格式为fileone.doc或filetwo.pdf。我需要确定在UITableView中正确显示相关图标的文件类型。以下是我迄今为止所做的工作。
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编程中使用过regex,所以我不完全确定我做得是否正确,但我基本上是从类描述页面复制代码的。
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);
我的问题是,有没有更简单的方法可以做到这一点?如果不是,我的正则表达式是否不正确?最后,如果我必须使用它,它在运行时成本高吗?我不知道一个用户的平均文件量是多少
谢谢。
您正在寻找[fileType pathExtension]
NSString文档:pathExtension
//NSURL *url = [NSURL URLWithString: fileType];
NSLog(@"extension: %@", [fileType pathExtension]);
编辑您可以在NSString上使用pathExtension
感谢David Barry
试试这个:
NSString *fileName = @"resume.doc";
NSString *ext = [fileName pathExtension];
试试这个,它对我有用。
NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
此处的NSString路径扩展文档
尝试使用[fileType pathExtension]获取文件的扩展名。
在Swift 3中,您可以使用一个扩展:
extension String {
public func getExtension() -> String? {
let ext = (self as NSString).pathExtension
if ext.isEmpty {
return nil
}
return ext
}
}