添加字符串分類
@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;
}