2011-01-12 3 views
3

Je veux extraire la chaîne entre crochets []Impossible d'extraire la chaîne en utilisant NSRegularExpression (motif regex) - iphone

pour l'exemple Chaîne d'origine: @ « Ceci est un test [pour obtenir cette chaîne]. »

Je veux obtenir une chaîne d'extraction entre [] i.e "pour obtenir cette chaîne" dans cet exemple.

S'il vous plaît trouverez ci-dessous mon code

NSMutableString *predicateString = [[NSMutableString alloc] initWithFormat:@"%@",@"this is a test [to get this string]."]; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[[^\].]*\]" 
        options:NSRegularExpressionCaseInsensitive 
        error:&error]; 


NSMutableArray *rangeArray = [[NSMutableArray alloc] init]; 
__block NSUInteger count = 0; 
[regex enumerateMatchesInString:predicateString options:0 range:NSMakeRange(0, [predicateString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){ 
    NSRange matchRange = [match range]; 
    matchRange.length = matchRange.length+1; 
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
    NSLog(@"matchRange.location: %d",matchRange.location); 
    NSLog(@"matchRange.length: %d",matchRange.length); 

    if (++count >= 100) *stop = YES; 

}]; 

S'il vous plaît laissez-moi savoir si je fais quelque chose de mal.

Merci.

Répondre

1

On dirait que l'expression est fausse, vous devez échapper les barres obliques (par exemple: @"\\[[^\\].]*\\]").

+0

Merci Marcelo ..... cela a fonctionné. – D25

Questions connexes