我搜索了高低,但找不到用于在目标C中剥离//和/ * * /注释的正确的正则表达式。
但是我找到了一个很好的答案Regex to strip line comments from C#,我将其移植到Objective C。
它没有那么优雅或写得很好,我很乐意得到关于如何改进它的反馈,所以我会把它作为答案发布,并希望它可以帮助某人
答案 0 :(得分:3)
好的 - 这里是:
+ (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;
}