2012-09-24 131 views
5

我需要確定是否文本是一個電子郵件地址,或手機號碼,電子郵件地址,我可以使用一些正則表達式,爲手機號碼,我可以檢查字符串只有數字(是嗎?)iOS:如何檢查一個字符串是否只有數字?

和順序是這樣的:

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

但我怎麼檢查,如果一個字符串中的iOS只有數字?

感謝

+1

對於第二位。可能重複的[如何檢查NSString是否是數字](http://stackoverflow.com/questions/2020360/how-to-check-if-nsstring-is-numeric-or-not)這本身就是一個騙局http://stackoverflow.com/questions/1320295/iphone-how-to-check-that-a-string-is-numeric-only - 請在下次詢問之前看看,我們並不是真的想要一百萬份每個問題:-) – paxdiablo

+0

首先,能夠正確處理電子郵件的正則表達式的長度大約爲270億個字符:-)對於檢查電子郵件的最佳方式是通過鏈接發送一些信息給它需要選擇。並非每個合法的電子郵件地址都有效 – paxdiablo

+0

如果電話號碼包含短劃線,該怎麼辦?還是括號? – borrrden

回答

10

您創建一個NSCharacterSet包含數字和可能的破折號,也許括號(取決於你所看到的格式的電話號碼)。然後你反轉這個集合,所以你有一個除了那些數字和事物以外都有的集合,然後使用rangeOfCharactersFromSet,並且如果你得到了除NSNotFound之外的任何東西,那麼你就擁有了除數字之外的東西。

+0

我想指出,基於語言環境,其他分隔符可能會用於電話號碼。例如在德國,我們使用斜線和/或空格。 – JustSid

+0

如何反轉該設置? – hzxu

+0

您使用NSCharacterSet方法invertedSet – rdelmar

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 
} 
相關問題