2016-09-16 8 views
0

NSLogがあるかどうかを確認しているので、コメントしています。 私はNSRegularExpressionを使用しており、結果をループしています。 コード:目的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]; 

} 

問題は、テストケースである。その代わりに、それは戻り"/*DSLog(@"A string");*/ /*DSLog(@"A string2")*/"を返す

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

"/*DSLog(@"A string"); NSLog(@"A string2")*/"

問題はObjective-Cが正規表現を処理する方法です。私はarrayOfAllMatchesの2つの結果を期待していましたが、代わりに1つしか得られません。 に);の最初の出現を停止するように依頼する方法はありますか?

答えて

1

問題は正規表現にあります。最初の閉じ括弧を含むようにし、2番目のNSLog文を続けて、最後の閉じ括弧に移動します。 )文字以外の括弧内のすべてのものを含めるようにそれを伝え

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

だから、あなたが何をしたいのか、このようなものです。その正規表現を使って、私は2つのマッチを得る。 (あなたの文字列のサンプルでは、​​最後を省略していることに注意してください)。

関連する問題