iOS-正規表示式使用

weixin_30639719發表於2020-04-05

正規表示式與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);
}

相關資料

常用正規表示式

轉載於:https://www.cnblogs.com/lancely/p/5782676.html

相關文章