电话不使用正则表达式进行验证-博士格式(974)041-0475 [英] Phone No validation with regular expression - Ph. Format (974) 041-0475

查看:50
本文介绍了电话不使用正则表达式进行验证-博士格式(974)041-0475的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

(974) 041-0475

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

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

推荐答案

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

这篇关于电话不使用正则表达式进行验证-博士格式(974)041-0475的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆