Get file extension contained in NSString

I have an NSMutable dictionary that contains file identifiers and their file name + extension in the simple form fileone.doc or filetwo.pdf. I need to determine what type of file the corresponding icon should display correctly in my UITableView. Here is what I have done so far.

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 

I wrote two regular expressions to determine what type of file I am looking for, but they never return a positive result. I have not used regex in iOS programming before, so I'm not quite sure that I am doing it right, but basically copied the code from the class description page.

  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); 

My questions would be, is there an easier way to do this? If not, is my regex wrong? And finally, if I have to use this, is it expensive at runtime? I don’t know how many files the user will have.

Thank.

+46
regex objective-c iphone ios5 nsstring
Feb 11 '12 at 23:52
source share
6 answers

You are looking for [fileType pathExtension]

NSString Documentation: Extension Path

+141
Feb 11 '12 at 23:59
source share
β€” -
 //NSURL *url = [NSURL URLWithString: fileType]; NSLog(@"extension: %@", [fileType pathExtension]); 

Change you can use pathExtension in NSString

Thanks David Barry

+6
Feb 11 2018-12-12T00:
source share

Try using [fileType pathExtension] to get the file extension.

+3
Feb 12 '12 at 0:00
source share

Try the following:

 NSString *fileName = @"resume.doc"; NSString *ext = [fileName pathExtension]; 
+3
Feb 04 '15 at 12:09
source share

In Swift 3, you can use the extension:

 extension String { public func getExtension() -> String? { let ext = (self as NSString).pathExtension if ext.isEmpty { return nil } return ext } } 
0
Jan 10 '17 at 18:12
source share

Try it, it works for me.

 NSString *fileName = @"yourFileName.pdf"; NSString *ext = [fileName pathExtension]; 

Documentation for NSString pathExtension

0
Mar 31 '17 at 19:54
source share



All Articles