检测 NSString 中的电话号码
我想从 NSString 中提取电话号码。
例如:在字符串 Call John @ 994-456-9966 中,我想提取 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];
但无法得到确切的结果。谁能帮助我吗?提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为这就是您正在寻找的:
您可以依赖 Cocoa 内置的默认正则表达式搜索机制。这样您就可以提取与电话号码对应的范围(如果存在)。
请记住在创建正则表达式时始终使用双转义反斜杠。
根据您要提取的电话号码部分相应地调整您的正则表达式。
Edit
Cocoa 提供了非常简单的工具来处理正则表达式。对于更复杂的需求,您应该查看 Cocoa 项目的强大 RegexKitLite 扩展。
This is what you are looking for, I think:
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.
你可以在iOS 4.0查看官方的NSDataDetector
You can check the official NSDataDetector in iOS 4.0
如果您只需要数字,您可以过滤掉特殊字符并使用 nsscanner
if u need just the number u can filter out the special characters and use nsscanner
假设您的所有电话号码中都有“@”符号。
或者
您可以使用 NSScanner 提取电话号码。
编辑:看到评论后。
假设您的手机号码只有 12 个字符。
Assume that you are having "@" symbol in all phone numbers.
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.