2013-04-12 21 views

回答

2

好的 - 在这里:

+ (NSString *) stripComments:(NSString *)text{ 

    NSString *blockComments = @"/[*](.*?)[*]/"; 
    NSString *lineComments = @"//(.*?)\r?\n"; 
    NSString *strings = @"\"((\\[^\n]|[^""\n])*)\""; 
    NSString *verbatimStrings = @"@(\"[^\"]*\")+"; 
    NSMutableArray *removes = [NSMutableArray array]; 

    NSError *error = NULL; 
    NSRegularExpression *regexComments = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"%@|%@|%@|%@",blockComments,lineComments,strings,verbatimStrings] options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators 
                       error:&error]; 

    NSArray* matches = [regexComments matchesInString:text options:0 range:NSMakeRange(0, text.length)]; 

    for (NSTextCheckingResult* match in matches){ 

     NSString *outer = [text substringWithRange:[match range]]; 
     if([outer hasPrefix:@"/*"] || [outer hasPrefix:@"//"]){ 
      [removes addObject:outer]; 
     } 
    } 

    for(NSString *match in [removes valueForKeyPath:@"@distinctUnionOfObjects.self"]){ 
     text = [text stringByReplacingOccurrencesOfString:match withString:@""]; 
    } 

    return text; 
}