iphone sdk - 从字符串中删除除数字0-9之外的所有字符 [英] iphone sdk - Remove all characters except for numbers 0-9 from a string

查看:109
本文介绍了iphone sdk - 从字符串中删除除数字0-9之外的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以这是计划。我从中获取数据的XML允许电话号码字段中的非数字文本(用于描述或联系人姓名等)。我试图只提取数字并用它们调用tel:URL来发起呼叫。这里有什么不工作:

OK So here's the plan. The XML I'm getting data from allows non-numeric text in phone number fields (for descriptions or contact names, etc). I am trying to extract only the numbers and call the tel: URL with them to initiate a call. Here's whats NOT working:

NSCharacterSet *charset = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString *number = @"(555) 555-5555 Office";
NSString *strippedNumber = [number stringByTrimmingCharactersInSet:charset];
NSString *phoneURL = [NSString stringWithFormat:@"tel:%@", strippedNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneURL]];

如果有任何明显的拼写错误,它们只是错别字。 :)

if there are any obvious typos, they're just typos. :)

推荐答案

您正在使用trim方法,这意味着它只查看字符串的外边缘。你可能得到类似的东西:555)555-555作为电话号码,对吗?

You're using a trim method, which means that it's only looking at the outer edges of the string. You're probably getting something like: "555) 555-555" as the phone number, correct?

我不知道NS(Mutable)String方法沿着replaceOccurrencesOfCharactersInSet:(NSCharacterSet *)set,我承认,这可能真的很棒。

I'm not aware of an NS(Mutable)String method along the lines of "replaceOccurrencesOfCharactersInSet:(NSCharacterSet *)set", and I admit, that'd probably be really nice to have.

作为我,我可能只需使用正则表达式。如果您使用 RegexKitLite ,那么您可以轻松地执行以下操作:

Being me, I'd probably just use a regex. If you use RegexKitLite, then you can easily do:

#import "RegexKitLite.h"

NSString * number = @"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfRegex:@"[^0-9]" withString:@""];

这可能有点矫枉过正,但它会完全符合您的要求。

It might be a bit overkill, but it will do exactly what you're looking for.

FYI:[^ 0-9]表示任何不是0,1,2,3,4,5,6,7,8或9的字符 。

FYI: "[^0-9]" means "any character that's not 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9".

这篇关于iphone sdk - 从字符串中删除除数字0-9之外的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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