0
我有NSString
我正在檢查是否有NSLog
,然後我將其註釋掉。 我正在使用NSRegularExpression
,然後遍歷結果。 代碼:Objective C - 具有特定子字符串的NSRegularExpression
-(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];
}
問題是與測試用例:
NSString *str = @"NSLog(@"A string"); NSLog(@"A string2")"
,而不是返回"/*DSLog(@"A string");*/ /*DSLog(@"A string2")*/"
它返回:"/*DSLog(@"A string"); NSLog(@"A string2")*/"
。
問題是Objective-C
如何處理正則表達式。我預計在arrayOfAllMatches
會有2個結果,但我只能得到一個結果。有沒有辦法在);
的第一次出現時詢問Objective-C
?