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

南笙酒味 提交于 2019-12-25 02:01:55

问题


Say I have this text:

word1 word2 " word3 //" word4

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

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


回答1:


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



来源:https://stackoverflow.com/questions/8030552/whats-a-good-regular-expression-for-comment-syntax-highlighting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!