0
我已搜查高和低,但不能找到一個很好的正則表達式剝離//和目的C.如何剝離從文件的註釋與NSRegularExpression
/* * /註釋中,但是我發現了一個偉大的答案Regex to strip line comments from C#我已將其移植到Objective C中。
這不是很優雅或寫得很好,我很想反饋如何改進,所以我會將它作爲答案發布,並希望它可以幫助某人
我已搜查高和低,但不能找到一個很好的正則表達式剝離//和目的C.如何剝離從文件的註釋與NSRegularExpression
/* * /註釋中,但是我發現了一個偉大的答案Regex to strip line comments from C#我已將其移植到Objective C中。
這不是很優雅或寫得很好,我很想反饋如何改進,所以我會將它作爲答案發布,並希望它可以幫助某人
好的 - 在這裏:
+ (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;
}