swift2.2
以邮箱为例:
func validateEmail(email: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluateWithObject(email)
}
使用:
func isEmail() {
if validateEmail(str!) == true {
print("str is Email!");
}else{
print("str is not Email")
}
}
若要判断其他的,修改正则表达式即可:
手机号:^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$
身份证号:^(\\d{14}|\\d{17})(\\d|[xX])$