1

我必须验证以下格式的电话号码

(974) 041-0475

我尝试过使用正则表达式@"^+(?:[0-9] ?){6,14}[0-9]$",但它不适用于上述示例。它适用于普通数字。

4

2 回答 2

1
You can use any of the regex according to your requirement
\(\d+\)\s*?\d+\-\d+
      OR
\(\d{3}\)\s*?\d{3}\-\d{4}   
于 2013-05-29T08:00:29.503 回答
0
US Phone Number Validation
NSString *unformatted = textField.text;//pass textfield object with text property
    NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
                                 [unformatted substringWithRange:NSMakeRange(3, 3)],
                                 [unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];

    NSString *formattedString = [NSString stringWithFormat:@"(%@)%@-%@",
    [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1],
    [stringComponents objectAtIndex:2]];NSLog(@"Formatted Phone Number: %@", formattedString);

- (BOOL) validatePhoneWithString:(NSString *)phone
{
    NSString *str = @"(([+]{1}|[0]{2}){0,1}+[1]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
    NSPredicate *no = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",str];
    return [no evaluateWithObject:phone];
}
于 2013-05-29T07:55:48.083 回答