1

I have searched high and low but can't find a good regex for stripping // and /* */ comments in Objective C.

However I found a great answer Regex to strip line comments from C# which I have ported to Objective C.

It's not as elegant or nicely written and I'd love to have feedback as to how it could be improved so I'll post it as an answer and hope it helps someone

Community
  • 1
  • 1
petenelson
  • 460
  • 2
  • 15

1 Answers1

4

Ok - here goes:

+ (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;
}
petenelson
  • 460
  • 2
  • 15