Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Phone number in a NSString

I want to extract the phone number from a NSString.

For ex: In the string Call John @ 994-456-9966, i want to extract 994-456-9966.

I have tried code like,

NSString *nameRegex =@"(\(\d{3}\)\s?)?\d{3}[-\s\.]\d{4}"; 
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"ANY keywords.name CONTAINS[c] %@",nameRegex]; 
validationResult=[nameTest evaluateWithObject:phoneNo]; 

but i couldnt get exact result. Can anyone help me? Thanks in advance.

like image 541
KingofBliss Avatar asked Dec 21 '22 12:12

KingofBliss


1 Answers

This is what you are looking for, I think:

NSString *myString = @"John @ 123-456-7890";
NSString *myRegex = @"\\d{3}-\\d{3}-\\d{4}";
NSRange range = [myString rangeOfString:myRegex options:NSRegularExpressionSearch];

NSString *phoneNumber = nil;
if (range.location != NSNotFound) {
    phoneNumber = [myString substringWithRange:range];
    NSLog(@"%@", phoneNumber);
} else {
    NSLog(@"No phone number found");
}

You can rely on the default Regular Expression search mechanism built into Cocoa. This way you will be able to extract the range corresponding to the phone number, if present.

Remember do alway double-escape backslashes when creating regular expressions.

Adapt your regex accordingly to the part of the phone number you'd like to extract.

Edit

Cocoa provides really simple tools for handling regular expressions. For more complex needs, you should look at the powerful RegexKitLite extension for Cocoa projects.

like image 182
marzapower Avatar answered Jan 08 '23 07:01

marzapower