2011-05-30 60 views
4

有什麼方法可以刪除給定目錄中的所有文件(不遞歸)使用模式?刪除與iOS中的模式匹配的文件

舉個例子,我有一個名爲file1.jpgfile2.jpgfile3.jpg等一些文件,我想知道如果有一個acceps通配符這樣的UNIX命令的任何方法:

rm file*.jpg 

回答

14

試試這個:

- (void)removeFiles:(NSRegularExpression*)regex inPath:(NSString*)path { 
    NSDirectoryEnumerator *filesEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:path]; 

    NSString *file; 
    NSError *error; 
    while (file = [filesEnumerator nextObject]) { 
     NSUInteger match = [regex numberOfMatchesInString:file 
                options:0 
                range:NSMakeRange(0, [file length])]; 

     if (match) { 
      [[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error]; 
     } 
    } 
} 

您例如

file1.jpg,file2.jpg,FIL e3.jpg

可以直接使用如下:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^file.*\.jpg$" 
                      options:NSRegularExpressionCaseInsensitive 
                      error:nil]; 
[self removeFiles:regex inPath:NSHomeDirectory()]; 
+0

輝煌!第二種解決方案簡直太棒了!謝謝! – SpaceDog 2011-05-31 02:17:38

0

斯威夫特版本

func removeFiles(regEx:NSRegularExpression, path:String) { 
    let filesEnumerator = NSFileManager.defaultManager().enumeratorAtPath(path) 
    while var file:String = filesEnumerator?.nextObject() as? String { 
     let match = regEx.numberOfMatchesInString(file, options: nil, range: NSMakeRange(0, file.length)) 
     if match > 0 { 
      NSFileManager.defaultManager().removeItemAtPath(path.stringByAppendingPathComponent(file), error: nil) 
     } 
    } 
} 
相關問題