Iphone 使用正则表达式验证电话号码-Ph格式(974)041-0475
我必须验证以下格式的电话号码Iphone 使用正则表达式验证电话号码-Ph格式(974)041-0475,iphone,objective-c,regex,validation,nspredicate,Iphone,Objective C,Regex,Validation,Nspredicate,我必须验证以下格式的电话号码 (974) 041-0475 我尝试过使用regex@“^+(?:[0-9]?){6,14}[0-9]$”,但对于上面的示例,它不起作用。它适用于普通数字。这似乎是复制粘贴的来源,请在逐字使用源代码时记入贷方。这似乎是复制粘贴的来源,请在逐字使用源代码时记入贷方。 US Phone Number Validation NSString *unformatted = textField.text;//pass textfield object with text p
(974) 041-0475
我尝试过使用regex
@“^+(?:[0-9]?){6,14}[0-9]$”
,但对于上面的示例,它不起作用。它适用于普通数字。这似乎是复制粘贴的来源,请在逐字使用源代码时记入贷方。这似乎是复制粘贴的来源,请在逐字使用源代码时记入贷方。
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];
}
You can use any of the regex according to your requirement
\(\d+\)\s*?\d+\-\d+
OR
\(\d{3}\)\s*?\d{3}\-\d{4}