iOS中正则表达式的三种使用方式

正则语法努力学习中

一:使用NSPredicate(谓词)匹配

 NSString *mail = @"zhangrongwuios@icloud.com";
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isValid = [predicate evaluateWithObject:mail];

二:rangeOfString: option: 进行搜索

 NSString *text = @"// Do any additional setup after loading the view, typically from a nib.";
    NSRange range  = [text rangeOfString:@"(?:[^,])*\\." options:NSRegularExpressionSearch];
    if (range.location != NSNotFound) {
        NSLog(@"%@", [text substringWithRange:range]);
    }

三:使用iOS系统正则表达类

   NSString *text = @"// Do any additional setup after loading the typically from a nib. view, typically from a nib.";
    NSError *error = NULL;
    NSRegularExpression *regx = [NSRegularExpression regularExpressionWithPattern:@"(?:[^,])*\\." options:NSRegularExpressionCaseInsensitive error:&error];
   
    // 匹配多个
    NSArray<NSTextCheckingResult *> *results = [regx matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    [results enumerateObjectsUsingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@", obj);
        if (obj) {
            NSLog(@"多次匹配结果 :%@", [text substringWithRange:obj.range]);
        }
    }];
   
    // 匹配单个
    NSTextCheckingResult *result = [regx firstMatchInString:text options:0 range:NSMakeRange(0, [text length])];
    if (result) {
        NSLog(@"%@", [text substringWithRange:result.range]);
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区