正则表达式提取电话号码

时间:2022-08-17 20:37:36

正则表达式提取电话号码方法:

+ (NSArray *) getPhoneNumbersFromString:(NSString *) str {

    NSError* error = nil;
    NSString* regulaStr = @"(([0-9]{11})|((400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})(-| )?)?([0-9]{7,8})((-| |转)*([0-9]{1,4}))?))";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

    NSArray *arrayOfAllMatches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
    NSMutableArray* numbers = [NSMutableArray arrayWithCapacity:arrayOfAllMatches.count];
    for (NSTextCheckingResult *match in arrayOfAllMatches)
    {
        NSString* substringForMatch = [str substringWithRange:match.range];
        [numbers addObject:substringForMatch];

    }

    return numbers;
}