Detect Phone number in a NSString

不羁的心 提交于 2019-12-03 03:52:07

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.

You can check the official NSDataDetector in iOS 4.0

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


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

Result: 555555555

if u need just the number u can filter out the special characters and use nsscanner

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

Assume that you are having "@" symbol in all phone numbers.

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

or

You can use the NSScanner to extract the phone number.

EDIT:After seeing the comments.
Assume that you are having only 12 characters in your mobile numbers.

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

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