删除与 iOS 中的模式匹配的文件 [英] Remove files matching a pattern in iOS

查看:59
本文介绍了删除与 iOS 中的模式匹配的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用模式删除给定目录中的所有文件(非递归)?

Is there any way to remove all files in a given directory (not recursively) using a pattern?

例如,我有一些名为 file1.jpgfile2.jpgfile3.jpg 等的文件,并且我想知道是否有任何方法可以接受像这个 UNIX 命令这样的通配符:

As an example, I have some files named file1.jpg, file2.jpg, file3.jpg, etc., and I want to know if there is any method that acceps wildcards like this UNIX command:

rm file*.jpg

推荐答案

试试这个:

- (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、file3.jpg

file1.jpg, file2.jpg, file3.jpg

您可以使用如下:

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

这篇关于删除与 iOS 中的模式匹配的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆