iOS-正则表达式使用

2016-04-19  本文已影响211人  lancely

正则表达式与NSPredicate连用

- (BOOL)validateNumber:(NSString *)textString {
    NSString *number = @"^[0-9]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}

正则表达式类

NSString *searchText = @"you want to match";    
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]+$" options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:searchText options:0 range:NSMakeRange(0, [searchText length])];
if (result) {
    NSLog(@"%@", [searchText substringWithRange:result.range]);
}

分组的使用

NSString *text = @"我是lancely";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^我是(.*?)$" options:kNilOptions error:nil];
NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:text options:kNilOptions range:NSMakeRange(0, text.length)];
if (matches.count) {
    NSRange regexGroupRange = [matches.firstObject rangeAtIndex:1];
    NSString *name = [text substringWithRange:regexGroupRange];
    NSLog(@"名字是:%@", name);
}

相关资料

常用正则表达式

上一篇下一篇

猜你喜欢

热点阅读