NSRegularExpression in Objective-C
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]]];
}];
Just like the code above the input string(self) is:
[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
and I want to get the for groups for [04:51.50][04:45.50][04:43.50][04:39.50]
but I can only get the last on [04:39.50]
Is the NSRegularExpression
can only get the last group when I search (($1)($2)($3)){2}
A repeated backreference only captures the last repetition. Your regex does match all four instances in that last line, but it overwrites each match with the next one, leaving only [04:39.50]
at the end.
Solution: Repeat a non-capturing group, and put the repeated result into the capturing group:
((?:\\[(\\d{2}):(\\d{2})\\.(\\d{2})\\])+)(.+)
You still can only access $2
through $4
for the last repetition, of course - but this is a general limitation of regexes. If you need to access each match individually, down to the minutes/seconds/frames parts, then use
((?:\\[\\d{2}:\\d{2}\\.\\d{2}\\])+)(.+)
to match each line first, and then apply a second regex to $1
in iteration to extract the minutes etc.:
\\[(\\d{2}):(\\d{2})\\.(\\d{2})\\]
精彩评论