What characters are allowed in a iOS file name?

Constantino Tsarouhas picture Constantino Tsarouhas · May 23, 2011 · Viewed 20.6k times · Source

I'm looking for a way to make sure a string can be used as a file name under iOS. I'm currently in the section of the code that deletes incompatible characters. I'm wondering if I'm doing it right.

NSString *filename = @"A file name";
fileName = [fileName stringByTrimmingCharactersInSet: [NSCharacterSet controlCharacterSet]];
fileName = [fileName stringByTrimmingCharactersInSet: [NSCharacterSet newlineCharacterSet]];

I'm also wondering if there's already a method that validates a string as a file name.

Thank you for your advice!

Answer

Abhi Beckert picture Abhi Beckert · Aug 30, 2013

Use RegEx:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^a-zA-Z0-9_]+" options:0 error:nil];
filename = [regex stringByReplacingMatchesInString:filename options:0 range:NSMakeRange(0, filename.length) withTemplate:@"-"];