2011-10-13 64 views
0
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]]]; 
}]; 

就像输入字符串(个体经营)上面的代码是:NSRegularExpression在Objective-C

[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}

回答

1

重复反向引用仅抓住了最后的R epetition。您的正则表达式匹配最后一行中的所有四个实例,但它会覆盖每个匹配的下一个匹配,最后只剩下[04:39.50]

解决方法:重复非捕获组,并把重复的结果为捕获组:

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

您仍然只能访问$2通过$4过去的重复,当然 - 但是这是一个正则表达式的一般限制。如果你需要单独访问每个匹配,精确到分/秒/帧的部分,然后用

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

首先匹配的每一行,然后再涂第二正则表达式来$1迭代中提取分钟等。 :

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