IOS: how to check if a string has only numbers?

I need to determine if the text is an email address or a mobile number for an email address, I can use some kind of regular expression, for a mobile number I can check if the string has only numbers (on the right?)

and the sequence is similar:

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

but how to check if the string only has iOS in iOS?

thank

+5
source share
2 answers

NSCharacterSet, , , , , ( , ). , , , , rangeOfCharactersFromSet, -, NSNotFound, - , .

+10

:

//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
}
+5

All Articles