【问题标题】:iOS: how to check if a string has only digits?iOS:如何检查字符串是否只有数字?
【发布时间】:2012-09-15 12:03:05
【问题描述】:

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

顺序如下:

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

但是如何在 iOS 中检查字符串是否只有数字?

谢谢

【问题讨论】:

  • 第二位。 How to check if NSString is numeric or not 的可能重复项,它本身就是 stackoverflow.com/questions/1320295/… 的重复项 - 请在下次询问之前查看,我们真的不想要每个问题的一百万份 :-)
  • 首先,能够正确处理电子邮件的正则表达式的长度大约为 270 亿个字符,这一点已得到公认:-) 检查电子邮件的最佳方法是使用需要选择的链接。并非每个合法的电子邮件地址都是有效的。
  • 如果电话号码包含破折号怎么办?还是括号?

标签: objective-c ios nsstring


【解决方案1】:

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

【讨论】:

  • 我想指出,根据语言环境,除破折号之外的其他分隔符可能用于电话号码。例如,在德国,我们使用斜线和/或空格。
  • 你使用的是NSCharacterSet方法invertSet
  • 如果字符串为@"",此检查结果为“是”,我认为这是不正确的
【解决方案2】:

这应该可行:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2023-03-23
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    相关资源
    最近更新 更多