面试题:oc正则匹配 删除注释

来源:互联网 发布:淘宝花呗怎么开通不了 编辑:程序博客网 时间:2024/04/30 00:21
//// 现有文件: '/Users/gb/Documents/oc_test/test.m',// 请编写程序,将'/Users/gb/Documents/oc_test/test.m' 文件中所有的取出去除,将结果写入'test.i'中(或者用 NSLog 函数在控制台输出)#import <AppKit/AppKit.h>#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) {    @autoreleasepool {        NSLog(@"hello!");                NSString *content=[NSString stringWithContentsOfFile:@"/Users/gb/Documents/oc_test/test.m" encoding:NSUTF8StringEncoding error:nil];        NSLog(@"content:%@",content);       NSString * regexStr = @"/\\*.*\\*/|//.*";                NSError *error = NULL;                NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];                NSArray *result=[regex matchesInString:content options:0 range:NSMakeRange(0, [content length])];                if (result) {                        for (NSTextCheckingResult* item in result)                            {//              str1 是每个和表达式匹配好的字符                NSString *str1 = [content substringWithRange:item.range];                                NSLog(@" str 1 is %@",str1);                            }                    }else{                        NSLog(@" 没有匹配到");        }            }       return 0;}



test.m文件

#import <Foundation/Foundation.h>// ;kjjk /*wertt /* ff  */ */ fasdfint main(int argc, const char * argv[]){    /*ggggg /* ddddd  */ // asdfee    int a; // define a;    NSLog(@"hello,world! /* "); // NSLog ;    /* return */    return 0;}


0 0
原创粉丝点击