2016-09-16 40 views
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

回答

1

問題出在正則表達式上。您正在搜索括號內的內容,這會導致它包含第一個關閉括號,繼續執行第二個NSLog語句,並一直到最後的關閉括號。

所以你想做的事是這樣的:

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

,告訴它包括括號內的所有內容除外)字符。使用該正則表達式,我得到兩個匹配。 (注意,你省略了最後的;在你的字符串示例中)。