我正在尝试创建一个函数,让用户在 Parse 中写下他们的社会安全号码,像这样:YYMMDD-XXXX
这是我的代码:
func isValidBirth() -> Bool {
let birthEX = "[00-99]+@[1-12]+@[1-31]+\-[0000-9999]"
let range = birthField!.rangeOfString(birthEX, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
}
每次我尝试注册时,我都会收到此错误,因为我没有正确填写我的社会安全号码。
我想我创建这个函数是错误的,因为我仍然是初学者。 :)
如何创建使用户写入其社会安全号码的函数?或者,如果我现在做对了,为什么它不起作用?
让我澄清一件事:你想要的不是美国式的社会安全号码。美国的SSN不包含生日。我将其解释为您想创建自己的SSN计划或其他国家/地区的SSN计划。
无论如何,不要指望正则表达式引擎将[00-99]
理解为"00 到 99"。方括号表示"匹配其中的任何字符"。这是正则表达式的解释方式:
[
0 - match the character 0; or
0-9 - match any character 0 to 9; or
9 - match the character 9
]
所以最后,这相当于[0-9]
.您需要修改正则表达式模式:
func isValidBirth(str: String) -> Bool {
let birthEx = "\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])-\d{4}"
let range = str.rangeOfString(birthEx, options:.RegularExpressionSearch)
return range != nil
}
isValidBirth("920101-1234") // true
isValidBirth("120231-4321") // true, but this is Feb 31 !!!
isValidBirth("151120-123") // false
关于正则表达式模式:
\d{2} - the year: any 2 digits
(0[1-9]|1[0-2]) - the month: 01 - 09, or 10 - 12
(0[1-9]|[1-2]\d|3[0-1]) - the day: 01 - 09, 10 - 29, or 30 - 31
- - the literal dash character
\d{4} - any four-digit number
有一些明显的警告:(1(当您以2位数格式编写年份时,确切的年份是模棱两可的。 15
可以是1915
的,也可以是2015
的;(2( 它不验证日期,这意味着 2 月 31 日是有效的日期。