NSRegularExpression 匹配正則表達式 oc iOS

1.簡單驗證手機號是否正確code

NSString *string = @"13156******";  //此處手機號作個屏蔽,
    NSString *regex = @"1[358][0-9]{9}";
    NSError *error;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
    if(error) return;
    NSInteger count = [regular numberOfMatchesInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)];
    NSLog(@"%ld",(long)count);

2.搜索字符串內部是否有手機號字符串

NSString *string = @"hahahahah13156******";
    NSString *regex = @"1[358][0-9]{9}";
    NSError *error;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
    if(error) return;
    
    [regular enumerateMatchesInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
        NSRange matchRange = result.range;
        NSLog(@"range:%@",NSStringFromRange(matchRange));
        NSString *resultString = [string substringWithRange:matchRange];
        NSLog(@"result ========   %@",resultString);
    }];

代碼運行一遍,resultString 就是我們要的手機號啦,開心不string

相關文章
相關標籤/搜索