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 );
?