iOS:如何检查字符串是否只有数字?

时间:2012-09-24 02:15:34

标签: objective-c ios nsstring

我需要确定文本是电子邮件地址还是手机号码,电子邮件地址我可以使用一些正则表达式,对于手机号码,我可以检查字符串是否只有数字(对吗?)

,顺序如下:

is (regex_valid_email(text))
{
    // email
}
else if (all_digits(text))
{
    // mobile number
}

但是如何检查字符串中是否只包含数字?

由于

2 个答案:

答案 0 :(得分:10)

您创建一个NSCharacterSet,其中包括数字,可能还有破折号和括号(取决于您看到的电话号码的格式)。然后你反转那个集合,所以你有一个除了那些数字和东西之外的所有东西的集合,然后使用rangeOfCharactersFromSet,如果你得到除NSNotFound之外的任何东西,那么你有除了数字之外的东西。

答案 1 :(得分:5)

这应该有效:

//This is the input string that is either an email or phone number
NSString *input = @"18003234322";

//This is the string that is going to be compared to the input string
NSString *testString = [NSString string];

NSScanner *scanner = [NSScanner scannerWithString:input];

//This is the character set containing all digits. It is used to filter the input string
NSCharacterSet *skips = [NSCharacterSet characterSetWithCharactersInString:@"1234567890"];

//This goes through the input string and puts all the 
//characters that are digits into the new string
[scanner scanCharactersFromSet:skips intoString:&testString];

//If the string containing all the numbers has the same length as the input...
if([input length] == [testString length]) {

    //...then the input contains only numbers and is a phone number, not an email
}