2011-10-13 62 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})\\]