iOS正则表达式捕获组

添加字符串分类

@interface NSString (Regex)

@end

@implementation NSString (Regex)

-(NSString *)substringWithRegex:(NSString *)regexStr {
    NSString *searchText = [self copy];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
     NSTextCheckingResult *result = [regex firstMatchInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
    if (!error && result) {
        NSRange matchRange = [result rangeAtIndex:1];
        NSString *matchString = [searchText substringWithRange:matchRange];
        NSLog(@"%@", matchString);
        NSString *matchStr = [searchText substringWithRange:result.range];
        return matchStr;
    }else {
        NSLog(@"%@",error);
    }
    return @"";
}
-(NSString *)substringWithRegex:(NSString *)regexStr rangeAtIndex:(NSInteger)idx {
    NSString *searchText = [self copy];
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
     NSTextCheckingResult *result = [regex firstMatchInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
    if (!error && result) {
        NSRange matchRange = [result rangeAtIndex:idx];
        NSString *matchString = [searchText substringWithRange:matchRange];
        if (matchString) {
            return matchString;
        }
    }
    return @"";
}
@end

测试获取类名和属性名

int main( ){
    NSString *line = @"@property (nonatomic, copy)  UIButton *     te_st1   ;";
    NSLog(@"%@",[line substringWithRegex:@"^@property.*?(?<=\\*)\\s*(\\w+)(?=\\s*;)" rangeAtIndex:1]);
    NSLog(@"%@",[line substringWithRegex:@"^@property.*?(?<=\\))\\s*(\\w+)(?=\\s*\\*)" rangeAtIndex:1]);
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。