2016-09-16 6 views
0

J'ai un NSString que je vérifie s'il y a un NSLog puis je le commente. J'utilise NSRegularExpression, puis je boucle le résultat. Le code:Objectif C - NSRegularExpression avec sous-chaîne spécifique

-(NSString*)commentNSLogFromLine:(NSString*)lineStr { 

    NSString *regexStr [email protected]"NSLog\\(.*\\)[\\s]*\\;"; 

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:nil]; 

    NSArray *arrayOfAllMatches = [regex matchesInString:lineStr options:0 range:NSMakeRange(0, [lineStr length])]; 

    NSMutableString *mutStr = [[NSMutableString alloc]initWithString:lineStr]; 

    for (NSTextCheckingResult *textCheck in arrayOfAllMatches) { 

     if (textCheck) { 
      NSRange matchRange = [textCheck range]; 
      NSString *strToReplace = [lineStr substringWithRange:matchRange]; 
      NSString *commentedStr = [NSString stringWithFormat:@"/*%@*/",[lineStr substringWithRange:matchRange]]; 
      [mutStr replaceOccurrencesOfString:strToReplace withString:commentedStr options:NSCaseInsensitiveSearch range:matchRange]; 

      NSRange rOriginal = [mutStr rangeOfString:@"NSLog("]; 
      if (NSNotFound != rOriginal.location) { 
       [mutStr replaceOccurrencesOfString:@"NSLog(" withString:@"DSLog(" options:NSCaseInsensitiveSearch range:rOriginal]; 
      } 
     } 
    } 

    return [NSString stringWithString:mutStr]; 

} 

Le problème est avec le cas de test:

NSString *str = @"NSLog(@"A string"); NSLog(@"A string2")" 

au lieu de retourner "/*DSLog(@"A string");*/ /*DSLog(@"A string2")*/" il retourne: "/*DSLog(@"A string"); NSLog(@"A string2")*/".

Le problème est de savoir comment le Objective-C gère l'expression régulière. Je m'attendais à 2 résultats dans arrayOfAllMatches mais à la place je n'en obtiens qu'un seul. Est-il possible de demander à Objective-C de s'arrêter à la première occurrence de );?

Répondre

1

Le problème est avec l'expression régulière. Vous recherchez. * Dans les parenthèses, ce qui l'amène à inclure la première parenthèse fermante, continue à travers la deuxième instruction NSLog, et va jusqu'aux parenthèses fermantes finales.

donc ce que vous voulez faire est quelque chose comme ceci: caractère

NSString *regexStr [email protected]"NSLog\\([^\\)]*\\)[\\s]*\\;"; 

Cela dit à tout inclure, entre parenthèses, sauf pour la). En utilisant cette regex, j'obtiens deux correspondances. (notez que vous avez omis la finale, dans votre exemple de chaîne).