Search code examples
iosregexsyntax-highlightingnsregularexpression

What's a good regular expression for comment Syntax Highlighting?


Say I have this text:

word1 word2 " word3 //" word4

I need write a regexp for comments. My solution now is ((\/\/).*(\n)), which results in enter image description here

regexp for text in "" next ((\").*(\"))


Solution

  • It's my solution. I know it can be better. I know about Back Reference but i don't have experience with it.

    NSRegularExpression *exp = [NSRegularExpression regularExpressionWithPattern:@"((@\"|\").*?(\"))"
                                              options:NSRegularExpressionDotMatchesLineSeparators 
                                                error:nil];
    NSArray *textArr = [exp matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    
    for (NSTextCheckingResult *result in textArr) {
        // set color for range
    }
    
    
    // Comments
    exp = [NSRegularExpression regularExpressionWithPattern:@"(//[^\"\n]*)"
                                                    options:0
                                                    error:nil];
    
    NSArray * arrayComments = [exp matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    
    for (NSTextCheckingResult *resultComment in arrayComments) {
    
        BOOL inside = NO;
        for (NSTextCheckingResult *resultText in textArr) {
            NSInteger from = resultText.range.location;
            NSInteger to = resultText.range.location+resultText.range.length;
            NSInteger now = resultComment.range.location;
            if (from < now && now < to) {
                inside = YES;
                break;
            }
        }
        if (!inside) {
            // set color for range
        }
    }
    

    answer on my blog