【问题标题】:I need the length of a NSRegularExpression result string我需要 NSRegularExpression 结果字符串的长度
【发布时间】:2016-09-18 11:45:58
【问题描述】:

我有很多文件,其中一些文件有这样的时间戳前缀:

1 20160308 1340 - All-of-me_key.pdf
2 2016 05 15 00 45 - nobody-knows-you-when-you-are-down-and-out.pdf

其他没有前缀:

- praying-for-time_key.pdf
- purple rain.pdf
- rehab.pdf

前缀的格式各不相同。如您在上面看到的,有些有空白作为分隔符,而另一些则有破折号。

我想自动化一个过程以从相关文件名中删除前缀。

出于解释的目的,我创建了两个正则表达式模式:

    atRegexArray = [NSArray arrayWithObjects:
                @"[0-9]{8} +[0-9]{4} - ",
                @"[0-9]{4} +[0-9]{2} +[0-9]{2} +[0-9]{2} +[0-9]{2} - ", nil ] ;

第一个模式检测第一种类型的前缀,第二种模式检测第二种类型的前缀。

第一类检测示例:

NSString * patternString = @"[0-9]{8} +[0-9]{4} - " ;
NSString *)theFileName   = @"20160308 1340 - All-of-me_key.pdf" ;

NSString *string = theFileName;
NSError *error = NULL;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:patternString
                                   options:NSRegularExpressionCaseInsensitive
                                   error:&error];

NSUInteger numberOfMatches = [regex numberOfMatchesInString:theFileName
                             options:0
                             range:NSMakeRange(0, [theFileName length])];

检测工作正常。问题是,我需要前缀的长度。 在此示例中,“20160308 1340 -”的长度为 16 在example2中“2016 05 15 00 45 -”的长度是19

我不知道如何自动获得这个长度。

有什么想法吗?

【问题讨论】:

  • 您需要this吗?

标签: objective-c regex string nsregularexpression


【解决方案1】:

如果你真的只想要前缀后面的字符串,你可以使用捕获括号。如果你想匹配一些特定的数字模式,那么只需包括那些由| 分隔的不同模式。例如:

NSArray *strings = @[@"20160308 1340 - All-of-me_key.pdf",
                     @"2016 05 15 00 45 - nobody-knows-you-when-you-are-down-and-out.pdf",
                     @"- praying-for-time_key.pdf"];

NSString *patternString = @"^(\\d{8} \\d{4} |\\d{4} \\d{2} \\d{2} \\d{2} \\d{2} )?(.*)$";

NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:patternString
                                                                       options:0
                                                                         error:&error];

for (NSString *string in strings) {
    NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];
    if (match) {
        NSLog(@"length of prefix = %ld", (long)[match rangeAtIndex:1].length);
        NSLog(@"stringAfterPrefix = '%@'", [string substringWithRange:[match rangeAtIndex:2]]);
    }
}

结果:

前缀长度 = 14 stringAfterPrefix = '- All-of-me_key.pdf' 前缀长度 = 17 stringAfterPrefix = '- 没有人知道你什么时候你倒下了.pdf' 前缀长度 = 0 stringAfterPrefix = '- 祈祷时间_key.pdf'

这个想法有很多排列方式(允许在前缀后使用可变数量的空格字符,也可以去掉前导短划线等),但希望这说明了使用捕获括号来查找文本的基本想法问题,以及使用| 来匹配潜在的多个不同前缀。

【讨论】:

  • 像魅力一样工作;))
猜你喜欢
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
相关资源
最近更新 更多