Define a phone number in NSString

I want to extract a phone number from NSString.

For example: in the line Call John @ 994-456-9966 , I want to extract 994-456-9966 .

I tried using the code,

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 could not get the exact result. Can someone help me? Thanks in advance.

+3
source share
5 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 Cocoa's default regular expression lookup engine. Thus, you can extract the range corresponding to the phone number, if any.

Remember that when creating regular expressions always execute double backslashes.

Adapt the regular expression to the part of the phone number you want to extract.

Cocoa . RegexKitLite Cocoa.

+4

NSDataDetector iOS 4.0

phoneLinkDetector = [[NSDataDetector alloc] initWithTypes:
          (NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber) error:nil];


NSUInteger numberOfPhoneLink = [[self phoneLinkDetector] numberOfMatchesInString:tweet
                          options:0  range:NSMakeRange(0, tweet.length)];
+3
NSString * number = @"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];

: 555555555

+2

, "@" .

NSString *list = @"Call John @ 994-456-9966";
NSArray *listItems = [list componentsSeparatedByString:@"@"] 

NSScanner .

EDIT: .
, 12 .

length=get the total length of the string.
index=length-12;

NSString *str=[myString substringFromIndex:index];
0

u, nsscanner

NSString *numberString = @"Call John @ 994-456-9966";
NSString *filteredString=[numberString stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSScanner *aScanner = [NSScanner scannerWithString:filteredString];
[aScanner scanInteger:anInteger];
0

All Articles