检测NSString中的电话号码 [英] Detect Phone number in a NSString

查看:90
本文介绍了检测NSString中的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从NSString中提取电话号码。

I want to extract the phone number from a NSString.

例如:在字符串致电John @ 994-456-9966 中,我想提取 994-456-9966

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

我尝试了类似的代码,

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.

推荐答案

这就是你要找的东西,我想:

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");
}

您可以依赖Cocoa内置的默认正则表达式搜索机制。通过这种方式,您将能够提取与电话号码相对应的范围(如果存在)。

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.

Cocoa提供了处理正则表达式的非常简单的工具。对于更复杂的需求,您应该查看针对Cocoa项目的强大的 RegexKitLite 扩展。

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

这篇关于检测NSString中的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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