Phone No validation with regular expression - Ph. Format (974) 041-0475 [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-11 10:52:58

问题


I have to validate a phone number which is in following format

(974) 041-0475

I have tried with regex @"^+(?:[0-9] ?){6,14}[0-9]$" but its not working for above example. It's working for plain digits.


回答1:


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];
}



回答2:


You can use any of the regex according to your requirement
\(\d+\)\s*?\d+\-\d+
      OR
\(\d{3}\)\s*?\d{3}\-\d{4}   


来源:https://stackoverflow.com/questions/16808218/phone-no-validation-with-regular-expression-ph-format-974-041-0475

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!