【问题标题】:Get the extension of a file contained in an NSString获取包含在 NSString 中的文件的扩展名
【发布时间】:2012-03-03 22:42:15
【问题描述】:

我有一个 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 编程中使用过正则表达式,所以我不完全确定我是否做得对,但我基本上是从 Class Description 页面复制了代码。

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

我的问题是,有没有更简单的方法来做到这一点?如果不是,我的正则表达式不正确吗?最后,如果我必须使用它,运行时间成本高吗?我不知道用户平均拥有多少文件。

谢谢。

【问题讨论】:

    标签: iphone objective-c regex ios5 nsstring


    【解决方案1】:

    您正在寻找[fileType pathExtension]

    NSString Documentation: pathExtension

    【讨论】:

    • 哦,不知道NSString有pathExtension属性
    • Objective-C 让事情变得如此简单;我不需要想到这么难的解决方案!谢谢大卫。
    • 我很高兴我没有尝试自己制作这个功能
    【解决方案2】:
    //NSURL *url = [NSURL URLWithString: fileType];
    NSLog(@"extension: %@", [fileType pathExtension]);
    

    编辑你可以在 NSString 上使用 pathExtension

    感谢大卫·巴里

    【讨论】:

    • 可以直接在String上调用pathExtension,不需要先创建NSURL。
    • 为什么你刚刚撕掉了上面的答案,然后记下了他的功劳?
    【解决方案3】:

    试试这个:

    NSString *fileName = @"resume.doc";  
    NSString *ext = [fileName pathExtension];
    

    【讨论】:

      【解决方案4】:

      试试这个,它对我有用。

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

      NSString pathExtension 的文档在这里

      【讨论】:

        【解决方案5】:

        尝试使用 [fileType pathExtension] 获取文件的扩展名。

        【讨论】:

          【解决方案6】:

          在 Swift 3 中,您可以使用扩展:

          extension String {
          
          public func getExtension() -> String? {
          
                  let ext = (self as NSString).pathExtension
          
                  if ext.isEmpty {
                      return nil
                  }
          
                  return ext
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-07-14
            • 2011-03-24
            • 2013-05-10
            • 2016-12-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多