【问题标题】:NSRegularExpression in Objective-CObjective-C 中的 NSRegularExpression
【发布时间】:2011-12-06 16:11:23
【问题描述】:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\[(\\d{2}):(\\d{2})\\.(\\d{2})\\])+(.+)" options:NSRegularExpressionAllowCommentsAndWhitespace error:&error];

[regex enumerateMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, [self length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
        [*lyricObject addObject:[self substringWithRange:[match rangeAtIndex:5]]];
        NSLog(@"%@",[self substringWithRange:[match rangeAtIndex:1]]);
        [*stamp addObject:[NSString stringWithFormat:@"%d", ([[self substringWithRange:[match rangeAtIndex:2]] intValue] * 60  +  [[self substringWithRange:[match rangeAtIndex:3]] intValue] ) * 100 + [[self substringWithRange:[match rangeAtIndex:4]] intValue]]];
}];

就像输入字符串(self)上面的代码是:

[04:30.50]There are pepole dying
[04:32.50]If you care enough for the living
[04:35.50]Make a better place for you and for me
[04:51.50][04:45.50][04:43.50][04:39.50]You and for me

我想获得[04:51.50][04:45.50][04:43.50][04:39.50] 的群组,但我只能在[04:39.50] 获得最后一个

NSRegularExpression在我搜索(($1)($2)($3)){2}时只能得到最后一组吗

【问题讨论】:

    标签: objective-c iphone regex nsregularexpression regex-group


    【解决方案1】:

    重复的反向引用仅捕获最后一次重复。您的正则表达式确实匹配最后一行中的所有四个实例,但它会用下一个匹配项覆盖每个匹配项,最后只留下 [04:39.50]

    解决方法:重复一个非捕获组,将重复的结果放入捕获组:

    ((?:\\[(\\d{2}):(\\d{2})\\.(\\d{2})\\])+)(.+)
    

    当然,对于最后一次重复,您仍然只能访问 $2$4 - 但这是正则表达式的一般限制。如果您需要单独访问每场比赛,精确到分钟/秒/帧部分,请使用

    ((?:\\[\\d{2}:\\d{2}\\.\\d{2}\\])+)(.+)
    

    首先匹配每一行,然后在迭代中将第二个正则表达式应用于$1 以提取分钟等:

    \\[(\\d{2}):(\\d{2})\\.(\\d{2})\\]
    

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 1970-01-01
      • 2012-03-05
      • 2014-01-06
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2012-07-17
      相关资源
      最近更新 更多